How do i close a figure shown using matplotlib in python ? And What is difference among image, figure and picture? - python-3.x

I am using ubuntu. I want to close a figure shown using matplotlib after few seconds without using keyboard or mouse. I am able to close an image shown using PIL after few seconds by getting its process id and then kill it.
And i am also little bit confused among terms figure, image and picture in matplotlib.
Thank you so much in advance.
Regarding part 1.
i have used plt.close(), plt.close("all") as well as 'psutil' library to fetch process ID and kill. But none of them worked. I got only solution of closing an image opened via 'PIL'.
link :-
How can I close an image shown to the user with the Python Imaging Library?
Regarding part 2.
Actually, at some pages, i found the terms 'figure','picture' and 'image' were used interchangeably; and at some pages they were not. I saw 'plt.imshow()' is used for image and picture and 'plt.show()' is used for figure. But, what is difference between figure, image and picture. And when to use these functions?
link :-
Why plt.imshow() doesn't display the image?
# for graphing
import matplotlib.pyplot as plt
import time
# for process
import psutil
# importing for image processing
from PIL import Image
#### closing an image which was opened via PIL
#### working perfectly
filename = "check.jpg"
img = Image.open(filename)
img.show()
time.sleep(5)
# for killing process such that image viewer
for proc in psutil.process_iter():
if proc.name() == "display":
proc.kill()
#### closing an image/figure which was opened via matplotlib
#### unable to close without keyboard or mouse
x = [[1,2,3,4],[11,22,33,44],[9,8,7,6]]
print (x)
plt.imshow(x)
plt.colorbar()
plt.title("a")
plt.xlabel('b')
plt.ylabel('c')
a = plt.show()
time.sleep(2)
## not working
plt.close()
## not working
for proc in psutil.process_iter():
if proc.name() == "display":
proc.kill()
## not working
plt.close("all")
i expect that my shown figure closes automatically after a few seconds,
instead of any manual intervention.

Related

PIL Python3 - How can I open a GIF file using Pillow?

In my current condition, I can open an Image normally using a really short code like this
from PIL import Image
x = Image.open("Example.png")
x.show()
But I tried to use GIF format instead of png, It shows the file but it didn't load the frame of the GIF. Is there any possible way to make load it?
In My Current Code
from PIL import Image
a = Image.open("x.gif").convert("RGBA") # IF I don't convert it to RGBA, It will give me an error.
a.show()
Refer to Reading Sequences in the documentation:
from PIL import Image
with Image.open("animation.gif") as im:
im.seek(1) # skip to the second frame
try:
while 1:
im.seek(im.tell() + 1)
# do something to im
except EOFError:
pass # end of sequence

cv2.cvtColor(img,cv2.COLOR_BGR2RGB) not working

I am trying to create a screen recorder using mss and Opencv in python, the video I am capturing has a very different colours than original computer screen. I tried to find the solution online, Everyone saying it should be fixed using cvtColor() but I already have it in my code.
import cv2
from PIL import Image
import numpy as np
from mss import mss
import threading
from datetime import datetime
`
def thread_recording():
fourcc=cv2.VideoWriter_fourcc(*'mp4v')
#fourcc=cv2.VideoWriter_fourcc(*'XVID')
out=cv2.VideoWriter(vid_file,fourcc,50,(width,height))
mon = {"top": 0, "left": 0, "width":width, "height":height}
sct = mss()
thread1=threading.Thread(target=record,args=(mon,out,sct))
thread1.start()
def record(mon,out,sct):
global recording
recording=True
while recording:
frame= np.array(sct.grab(mon))
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(frame)
out.release()
the vid_file variable contains a string of output file name with mp4 extension
Screenshot of my screen
Screenshot from recorded video
So, I looked around some more and found that apparently this is a bug in opencv for versions 3.x on wards.then I tried PIL for getting rgb image and removed cvtColor(),but it produced an empty video.I removed both cvtColor() as well as PIL Image as suggested by #ZdaR it again wrote empty video Hence I had to put it back and boom. even if cvtColor() seems like doing nothing, for some unknown reason it has to be there.when you use PIL Image along with cvtColor() it writes the video as expected
from PIL import Image
def record(mon,out,sct):
global recording
recording=True
while recording:
frame=sct.grab(mon)
frame = Image.frombytes('RGB', frame.size, frame.rgb)
frame = cv2.cvtColor(np.array(frame), cv2.COLOR_BGR2RGB)
out.write(np.array(frame))
out.release()
as I am very new to programming, I would really appreciate your help if I missed or overlooked something important
You can do
frameRGB = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
Frame is in BGR, and it will work the same as you are only changing R with B where frameRGB is in RGB now. This command will transfer R to B and works to transfer frames from RGB and BGR as well as BGR to RGB. BGR2RGB might be a bug, I have it as well but the command I mentioned works perfectly. That's what I do.
MSS store raw BGRA pixels. Does it work if you change to:
# Grab it
img = np.array(sct.grab(mon))
# Convert from BGRA to RGB
frame = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
you should run this command in cmd
pip install opencv-python

Displaying both plt.show() images as Figure 1, Figure 2 at the same time

Running the following code, I am unable to display both images at the same time in separate windows, or go from figure1 to figure2 with the arrow button.
Currently I am able to get figure2, only when I close figure1.
I have tried the following code to generate separate "figure" labels.
from skimage import data, color, io
from matplotlib import pyplot as plt
rocket = data.rocket()
gray_scale_rocket = color.rgb2gray(rocket)
f1=plt.figure(1)
io.imshow(rocket)
plt.show()
f2=plt.figure(2)
io.imshow(gray_scale_rocket)
plt.show()
I expect to see two windows figure1 and figure2 to be viewable at the same time (without needing to close figure1 window first), displaying the rocket image in color and in grayscale.
You should remove the first call to plt.show(), which is blocking (meaning it stops execution until you are done with the window). When you leave only the second one, it will show both figures simultaneously.
The resulting code:
from skimage import data, color, io
from matplotlib import pyplot as plt
rocket = data.rocket()
gray_scale_rocket = color.rgb2gray(rocket)
f1=plt.figure(1)
io.imshow(rocket)
f2=plt.figure(2)
io.imshow(gray_scale_rocket)
plt.show()
behaves as you expect.

How to overlay images on each other in python and opencv?

I am trying to write images over each other. Ideally, what I want to do is to write every image in one folder over every image in another folder and output every unique image to another folder. So far, I am just working on having one image write over one image, but I can't seem to get that to work.
import numpy as np
import cv2
import matplotlib
def opencv_createsamples():
mask = ('resized_pos/2')
img = cv2.imread('neg/1')
new_img = img * (mask.astype(img.dtype))
cv2.imwrite('samp', new_img)
opencv_createsamples()
It would be helpful to have more information about your errors.
Something that stands out immediately is the lack of file type extensions. Your images are probably not being read correctly, to begin with. Also, image sizes would be a good thing to consider so you could resize as required.
If the goal is to blend images, considering the alpha channel is important. Here is a relevant question on StackOverflow:How to overlay images in python
Some other OpenCV docs that have helped me in the past: https://docs.opencv.org/trunk/d0/d86/tutorial_py_image_arithmetics.html
https://docs.opencv.org/3.1.0/d5/dc4/tutorial_adding_images.html
Hope this helps!

Python3x + MatPlotLib - Updating a chart?

I am new to both the python and matplotlib languages and working on something for my husband.
I hope you guys can help me out.
I would like to pull in a file using Open, read it, and update a graph with it's values.
Sounds easy enough right? Not so much in practice.
Here is what I have so far to open and chart the file. This works fine as it is to chart the file 1 time.
import matplotlib.pyplot as plt
fileopen = open('.../plotresults.txt', 'r').read()
fileopen = eval(fileopen) ##because the file contains a dict and security is not an issue.
print(fileopen) ## So I can see it working
for key,value in fileopen.items():
plot1 = value
plt.plot(plot1, label=str(key))
plt.legend()
plt.show()
Now I would like to animate the chart or update it so that I can see changes to the data. I have tried to use matplotlib's animation feature but it is advanced beyond my current knowledge.
Is there a simple way to update this chart, say every 5 minutes?
Note:
I tried using Schedule but it breaks the program (maybe a conflict between schedule and having matplotlib figures open??).
Any help would be deeply appreciated.
Unfortunately you will just waste time trying to get a clean solution without either using matplotlib's animation feature or using the matplotlib OO interface.
As a dirty hack you can use the following:
from threading import Timer
from matplotlib import pyplot as plt
import numpy
# Your data generating code here
def get_data():
data = numpy.random.random(100)
label = str(data[0]) # dummy label
return data, label
def update():
print('update')
plt.clf()
data, label = get_data()
plt.plot(data, label=label)
plt.legend()
plt.draw()
t = Timer(0.5, update) # restart update in 0.5 seconds
t.start()
update()
plt.show()
It spins off however a second thread by Timer. So to kill the script, you have to hit Ctrl-C twice on the console.
I myself would be interested if there is a cleaner way to do this in this simple manner in the confines of the pyplot machinery.
Edits in italic.

Resources