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

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.

Related

Attempting to convert an image to grayscale, or better, binary

My basic plan here is to create an image recognition software that tracks the size of different bubbles. I basically have a compilation of pictures that constitute a video. I have it working as of right now using PIMS to import the files I need and place them into an array (rawframes). I can print my picture.
import numpy as np
import pandas as pd
import pims
from pims import pipeline
import trackpy as tp
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
#pipeline
def binary(frame):
return frame[:, :, 1]
id_example = 1
rawframes = pims.ImageSequence(os.path.join('BubbleSize/90FoamQuality/DryFoams', 'T20190411_002_ (*).jpg'), process_func=binary)
plt.imshow(rawframes[id_example])
What I am trying to do here is convert the images from regular into black and white. I have not used many of the things I imported yet I know, this is a very preliminary step.
However, below is a before and after image comparison. Can someone help me out or walk me through these steps here? I get lost when it comes to filtering the images through python.
edit --> when I change my pipeline function to the below, I get the same green image
edit2 --> printing frame.shape and frame.dtype in binary pipeline respectively

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

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.

Why will Seaborn function 'regplot' not run in Jupyter?

I am having trouble with code Seaborn regplot function in Jupyter notebooks using Watson-Studio.
Using Python 3.6, the code appears to get stuck whilst processing, and this happens until I stop the code.
When I run this using IDLE on my Mac, the code runs perfectly and the plot shows.
Seems to happen with plots lmplot and regplot, however boxplots etc do show as normal.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
df = pd.read_csv(csv.csv)
sns.regplot(x = 'independent', y = 'dependent', data = df)
The expected results should be a graph of the linear relationship between the two variables, however I am just getting a loading bar.
When I stop running the kernel, the graph exists as a scatterplot with no line of best fit. Of course this has the error in notebook as 'Keyboard Interrupted'.
Could this possibly be a bug? Thanks for your help.
Set ci parameter to none and it will solve your problem.
sns.regplot(x = 'independent', y = 'dependent', data = df, ci = None)

pdf not responsive when getting multiple pages in it using savefig

I am using matplotlib pyplot to generate plots. I want all my plots to come in a single pdf so I am using PdfPages. I am able to generate a single pdf with multiple plots but when the number of pages increase in the pdf it takes time to respond,.i.e, It opens and displays the first page of the pdf but when I try scrolling to go to other pages I have to wait for some time to see all the pages. The code I used is
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
plt.figure(figsize=(16, 9))
ax = plt.subplot(121)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
dataframe.plot.scatter(x=numericColumn2, y=numericColumn1, ax = ax)
plt.close()
pdf.savefig()
pdf.close()
Is there some parameter or something else I can add so that pdf does not takes time o respond?

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