FuncAnimation issues - python-2.7

I'm trying to make a little movie out of 15 (in this case) images that I obtained by color mapping matrices and the problem is that whatever the input series of images, the movie I obtain always stops after showing 13 images (it is the case for every tried number if I have n images, the movie shows only the n-2 first ones).
This is my piece of code:
im = plt.imshow(matrix_list[0],cmap=cm.hot_r,interpolation='none')
plt.colorbar()
#matrix_list is a list of 15 ndarrays of shape (15,15)
def updatefig(j):
# set the data in the axesimage object
im.set_array(matrix_list[j])
# return the artists set
return im,
# kick off the animation
ani = animation.FuncAnimation(fig, updatefig,frames=range(len(matrix_list)),
interval=1000, blit=True)
mywriter = animation.FFMpegWriter(fps=2.)
ani.save('my_movie_test.avi',writer=mywriter)

Related

Generating the background of imatest color error chart generated by using color checker?

I am having some trouble finding the background of the following plot made using imatest. Basically what I want to know is that how, or from where, can I find the background of this plot. The imatest website mentions that the colors of the chart are generated at a constant Luminance L* = 90 and by varing a* and b* from -80 to +80. I have been looking for Lab color generator but all software generate colored points. But I want to get a continuous image by varying the a and b values. Any idea?
Using matlab you can simply transform your cielab space into RGB space:
range = -80:0.5:80; % a,b range, change the step to change the size of the output image.
L = 100*ones(size(range,2),size(range,2)); % L intensity
[b,a] = meshgrid(range); % generate a 2D grid
Lab = cat(3,L,a,b); % create the 3D Lab array
I = lab2rgb(rot90(Lab)); % Lab -> RGB
imshow(I) % Display the result
And we obtain:
Just for fun, if anyone wants a Python OpenCV version, I made one like this:
#!/usr/bin/env python3
import cv2
import numpy as np
# Set size of output image
h, w = 500, 500
# Create "L" channel, L=90
L = np.full((h,w), 90.00, np.float32)
# Create "a" channel, -80 to +80
a = np.linspace(-80,80,w,endpoint=True,dtype=np.float32)
a = np.resize(a,(h,w))
# Create "b" channel by rotating "a" channel 90 degrees
b = cv2.rotate(a, cv2.ROTATE_90_COUNTERCLOCKWISE)
# Stack the 3-channels into single image and convert from Lab to BGR
res = np.dstack((L,a,b))
res = cv2.cvtColor(res, cv2.COLOR_LAB2BGR)
# Save result
cv2.imwrite('result.png', (res*65535).astype(np.uint16))

Extracting output before the softmax layer, then manually calculating softmax gives a different result

I have a model trained to classify rgb values into 1000 categories.
#Model architecture
model = Sequential()
model.add(Dense(512,input_shape=(3,),activation="relu"))
model.add(BatchNormalization())
model.add(Dense(512,activation="relu"))
model.add(BatchNormalization())
model.add(Dense(1000,activation="relu"))
model.add(Dense(1000,activation="softmax"))
I want to be able to extract the output before the softmax layer so I can conduct analyses on different samples of categories within the model. I want execute softmax for each sample, and conduct analyses using a function named getinfo().
Model
Initially, I enter X_train data into model.predict, to get a vector of 1000 probabilities for each input. I execute getinfo() on this array to get the desired result.
Pop1
I then use model.pop() to remove the softmax layer. I get new predictions for the popped model, and execute scipy.special.softmax. However, getinfo() produces an entirely different result on this array.
Pop2
I write my own softmax function to validate the 2nd result, and I receive an almost identical answer to Pop1.
Pop3
However, when I simply calculate getinfo() on the output of model.pop() with no softmax function, I get the same result as the initial Model.
data = np.loadtxt("allData.csv",delimiter=",")
model = load_model("model.h5")
def getinfo(data):
objects = scipy.stats.entropy(np.mean(data, axis=0), base=2)
print(('objects_mean',objects))
colours_entropy = []
for i in data:
e = scipy.stats.entropy(i, base=2)
colours_entropy.append(e)
colours = np.mean(np.array(colours_entropy))
print(('colours_mean',colours))
info = objects - colours
print(('objects-colours',info))
return info
def softmax_max(data):
# calculate softmax whilst subtracting the max values (axis=1)
sm = []
count = 0
for row in data:
max = np.argmax(row)
e = np.exp(row-data[count,max])
s = np.sum(e)
sm.append(e/s)
sm = np.asarray(sm)
return sm
#model
preds = model.predict(X_train)
getinfo(preds)
#pop1
model.pop()
preds1 = model.predict(X_train)
sm1 = scipy.special.softmax(preds1,axis=1)
getinfo(sm1)
#pop2
sm2 = softmax_max(preds1)
getinfo(sm2)
#pop3
getinfo(preds1)
I expect to get the same output from Model, Pop1 and Pop2, but a different answer to Pop3, as I did not compute softmax here. I wonder if the issue is with computing softmax after model.predict? And whether I am getting the same result in Model and Pop3 because softmax is constraining the values between 0-1, so for the purpose of the getinfo() function, the result is mathematically equivalent?
If this is the case, then how do I execute softmax before model.predict?
I've gone around in circles with this, so any help or insight would be much appreciated. Please let me know if anything is unclear. Thank you!
model.pop() does not immediately have an effect. You need to run model.compile() again to recompile the new model that doesn't include the last layer.
Without the recompile, you're essentially running model.predict() twice in a row on the exact same model, which explains why Model and Pop3 give the same result. Pop1 and Pop2 give weird results because they are calculating the softmax of a softmax.
In addition, your model does not have the softmax as a separate layer, so pop takes off the entire last Dense layer. To fix this, add the softmax as a separate layer like so:
model.add(Dense(1000)) # softmax removed from this layer...
model.add(Activation('softmax')) # ...and added to its own layer

How to click images in open cv python after a certain interval of time and simaltaneously save a fixed number of those captured images?

Since I am very much new to this language, with whatever little knowledge I have, I have written code.
The code is getting executed thrice, but the three images are being overwritten and at the end there is just one image that is available instead of 3 different images (which is my goal).
import cv2
#helps in turning on the camera
cap = cv2.VideoCapture(0)
#camera clicks the images for 3 times
a = 0
while (a < 3):
a = a+1
#creating a frame
check, frame = cap.read()
print(check)
print(frame)
#conversion of image to grayscale
image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#shows the frame
cv2.imshow("capturing",image)
#Saving Of image
status = cv2.imwrite('path of where the image is to be saved.jpg',image)
print("Image written to file-system : ",status)
#turns off the camera
cap.release
cv2.waitKey(0)
cv2.destroyAllWindows()

Data duplicated(doubled) in Dataset.next_batch() method

Assume that I have given only one test image.
I extract images,labels using mnist.test.next_batch(100).
When i give 1 test image, I am getting 2 images (same image duplicated)
When I give 2 test images, I am getting 4 (2 images duplicated).
Same problem exists for training images.
I consoled the length of test images and train images inside read_data_sets method(...tensorflow/contrib/learn/python/learn/datasets/mnist.py).
It is giving correct length.
Here is my code.
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, validation_size=0)
images, labels = mnist.test.next_batch(100)
print len(images) #double the actual length

Unable to set the Entry box to correct position in python

I am trying to learn creating GUI using Tkinter .I created a window which includes text,Messagebox,Entry widget,labels and Radio buttons.
I used grid method for frames and tried to make entry boxes in row0 and row1 .And a message Box with Some text.But these are not properly aligned even though i gave correct rows and columns but output is not in order.
Entry box is created very far though i mentioned column1 .And message box is created as per the column specified.Can anyone help me how to solve this.If i am missing anything please let me now .
from Tkinter import*
import tkMessageBox
class Example:
def __init__(self,root):
root.title("Sample")
#Entry functions ---------------------------------------
Label(root, text="First Name").grid(row=0)
Label(root, text="Last Name").grid(row=1)
self.e1 = Entry(root)
self.e1.bind("<Return>",self.ShowChoice_radio)
self.e2 = Entry(root)
self.e2.bind("<Return>",self.ShowChoice_radio)
self.e1.grid(row=0,column=1)
self.e2.grid(row =1,column = 1)
#------------------------------------------------------------------------
self.frame=Frame(root)
self.frame.grid(row=3,sticky=W)
self.label=Label(self.frame, text="mine", width=12,bg="green",fg="white",justify=LEFT)
self.label.grid(row=3,column=4,sticky=W,pady=4)
root.minsize(width=666, height=220)
self.v=IntVar()
role=[("ENGLISH",1),("SPANISH",2),("GERMAN",3)]
Label(self.frame,text="Choose your role of target:",justify=LEFT,padx=2,pady=2).grid(row=4,sticky=W)
i=0
for txt,val in role:
i=i+1
self.rad_bt=Radiobutton(self.frame,text=txt,padx=20,variable=self.v,
command=self.ShowChoice_radio,value=val)
self.rad_bt.grid(row=4,column=i+1)
self.bottomframe = Frame(root)
self.bottomframe.grid(row=12,sticky=W)
self.hello(12)
T=Text(self.bottomframe,height=2,width=30)
T.pack(padx=100,side=TOP)
T.insert(END,"just a normal text to display!\n")
self.mbutton=Button(self.bottomframe,text='Quit',command=self.callback,state='normal')
self.mbutton.pack(padx=3,pady=3,side='left')
self.help=Button(self.bottomframe,text='Help',command=self.help_msg,width=5,justify=CENTER)
self.help.pack(padx=93,pady=3,side='left')
def ShowChoice_radio(self):
print self.v.get()
def help_msg(self):
tkMessageBox.showinfo("Help to print ",message="Not yet implemented")
root.minsize(width=666, height=666)
self.show_entry_fields()
self.help.config(state=DISABLED)
def callback(self):
if tkMessageBox.askyesno('verify','Really Quit?'):
root.destroy()
def hello(self,name):
w=Label(root,text="Hello Tkinter!",width=15).grid(row=10)
whatever_you_do = "Whatever . it is my test that \n i can anble to display manner in this case find out whether it is correct one or wrong \n)"
msg=Message(root, anchor='s',width=200,text = whatever_you_do)
msg.config(bg='lightgreen', font=('times', 14, 'italic'))
msg.grid(row=10,column=1,sticky=W)
def show_entry_fields(self):
print "First Name: %s\nLast Name: %s" % (self.e1.get(), self.e2.get())
if __name__=="__main__":
root=Tk()
app=Example(root)
root.mainloop()
Even the quit and Help buttons are not proper...!!!
I initially voted to close this because there is not a clear question, but mostly only a series of statements and opinions, at least one of which is incorrect. After looking more, I think I can answer your implied question "Why is tkinter behaving in a way that seems wrong to me?". The answer, I believe, is that you do not understand that grid coordinates are independent (start over) for each container gridded. Also, coordinates not used are ignored. In particular:
Root has a grid of 5 rows and 2 columns. Renumbering the rows 0, 1, 2, 3, 4 instead of the confusing labeling you used, there is no entry in column 1 for rows 2 and 4. The width of column 0 is determined by the width of self.frame in row 2, column 0. The entry boxes are far to the right because column 0 is very wide.
Self.frame has a grid of 2 rows and 4 columns. The first 3 columns of row 0 are empty. Self.bottomframe is packed instead of gridded. The buttons are to the left of where you want because you packed them to the left. In other words, tkinter did just what you said, which is apparently not what you want.
You might list the result better if you got rid of self.frame, put 'mine' in (2,0) or (2,0), 'Choose...' in (3, 0), and a frame with 3 radio buttoms in (3,1). Then root column 0 would not be so overly wide.