I've been trying to iterate over files in a folder and show them for two seconds each using this code:
import time
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import imread
import glob
import cv2
im = []
for filepath in glob.iglob(r'C:\Users\dan20\Pictures\wedding\beeri and adn. photo/*.jpg'):
a = imread(filepath)
b = cv2.resize(a, dsize = (456,304))
im += [b]
fig,ax = plt.subplots()
for i in im:
time.sleep(2)
ax.axis('off')
ax.imshow(i)
plt.show()
For some reason I can't see the images as long as i use time.sleep().
How can I make each picture to appear for N amount of times?
How about using plt.pause :
import numpy as np
from matplotlib import pyplot as plt
im = [np.random.random((9,9)) for i in range(1,6)]
fig,ax = plt.subplots()
for i in im:
ax.cla()
ax.imshow(i)
ax.axis('off')
plt.pause(2)
which gives :
Related
import os
import imageio.v2 as imageio
import matplotlib.pyplot as plt #for displaying figure/image data
import pandas as pd
import plotly
import plotly.express as px
import plotly.graph_objects as go #for intearctive plots
import scipy.stats as ss # for statistical testing
import scikit_posthocs as so # for posthoc testing
from skimage import measure, morphology
from skimage.color import rgb2gray
from skimage.filters import (gaussian, threshold_yen)
from skimage.measure import regionprops_table
path = r'/Users/marzo/Downloads'
os.chdir(path)
imagename = 'Fish 2'
image = imageio.imread(imagename+'.jpg')
img = rgb2gray(image)
img= gaussian(img, sigma=1)
plt.imshow(img, cmap='gray')
block_size = 51
threshold = threshold_yen(img, block_size)
mask = img < threshold * 0.59
mask = morphology.remove_small_objects(mask, 400)
mask = morphology.remove_small_holes(mask, 5000)
plt.imshow(mask, cmap='gray')
I am trying to open an image using plt.imshow, but nothing is happening and I am not getting any errors though, can someone explain why is it not showing any images
I'm reading and output the picture as a plot:
import numpy as np
import os
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
fig, ax = plt.subplots()
path = 'photo.jpg'
im = plt.imread(path)
ax.imshow(im)
Output
After I want to save it and check(see) the image before saving, but my code generate empty image:(
plt.axis("off")
plt.gca().xaxis.set_major_locator(tkr.NullLocator())
plt.gca().yaxis.set_major_locator(tkr.NullLocator())
filename = os.path.basename(path).split(".")[0]
output_path = os.path.join("test", filename+".png").replace("/", "")
plt.savefig(output_path, bbox_inches="tight", pad_inches=0.0)
plt.show()
plt.close()
Output
Is it necessary to read the image as a graph?
If not, just use PIL library. It is a way more simpler to use:
You can check the code there: https://colab.research.google.com/drive/1Dmhb4aiERRym9bNx5HgCQPOr9iANHMic?usp=sharing
PIL documentation: https://pillow.readthedocs.io/en/stable/handbook/tutorial.html
I wonder if there is a possibility to set the color of a histgram, which is filled in a for loop, at the end of this process like:
import numpy as np
import matplotlib.pylot as plt
x=np.array([[1,1,3,4],[1,4,5,6],[1,4,4,6]])
plt.figure()
for i in range(3):
plt.hist(x[i])
plt.show()
Maybe some comand before the plt.show() ?
You could get hold of the Patch objects which make up the histogram as you go along:
import numpy as np
import matplotlib.pyplot as plt
x=np.array([[1,1,3,4],[1,4,5,6],[1,4,4,6]])
plt.figure()
patches = []
for i in range(3):
_, _, p = plt.hist(x[i])
patches += p
for patch in patches:
patch.set_color('pink')
plt.show()
plt.hist() has the parameter color:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[1,1,3,4],[1,4,5,6],[1,4,4,6]])
xcolor = ["r", "b", "y"]
plt.hist(x.T, color = xcolor)
plt.show()
This parameter works also in a loop, though the code you provided doesn't produce what you probably expect it to do.
Consider the following code:
import numpy as np
rand_matrix = np.random.rand(10,10)
which generates a 10x10 random matrix.
Following code to display as colour map:
import matplotlib.pyplot as plt
plt.imshow(rand_matrix)
plt.show()
I would like to get the RGB numpy array (no axis) from the object obtained from plt.imshow
In other words, if I save the image generated from plt.show, I would like to get the 3D RGB numpy array obtained from:
import matplotlib.image as mpimg
img=mpimg.imread('rand_matrix.png')
But without the need to save and load the image, which is computationally very expensive.
Thank you.
You can save time by saving to a io.BytesIO instead of to a file:
import io
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
def ax_to_array(ax, **kwargs):
fig = ax.figure
frameon = ax.get_frame_on()
ax.set_frame_on(False)
with io.BytesIO() as memf:
extent = ax.get_window_extent()
extent = extent.transformed(fig.dpi_scale_trans.inverted())
plt.axis('off')
fig.savefig(memf, format='PNG', bbox_inches=extent, **kwargs)
memf.seek(0)
arr = mpimg.imread(memf)[::-1,...]
ax.set_frame_on(frameon)
return arr.copy()
rand_matrix = np.random.rand(10,10)
fig, ax = plt.subplots()
ax.imshow(rand_matrix)
result = ax_to_array(ax)
# view using matplotlib
plt.show()
# view using PIL
result = (result * 255).astype('uint8')
img = Image.fromarray(result)
img.show()
How to set matplotlib to show every image of an array?
I want that everytime i click on the right arrow, it shows the next image and so on...
Is that possible?
width = 14
height = 14
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
data_images = X_train.reshape(X_train.shape[0],width,height)
print "Shape " ,data_images.shape #Shape (50000L, 14L, 14L)
plt.imshow(data_images[0])
plt.show()
I wanted to pass the "data_images" variable to plt.imshow and so everytime i clicked on next on the matplotlib, it would show the next image.
Working example with plt.connect().
You can change image by pressing any key.
import matplotlib.pyplot as plt
data_images = [
[[1,2,3],[1,2,3],[1,2,3]],
[[1,1,1],[2,2,2],[3,3,3]],
[[1,2,1],[2,2,2],[1,2,1]],
]
#----------------------------------
index = 0
def toggle_images(event):
global index
index += 1
if index < len(data_images):
plt.imshow(data_images[index])
plt.draw()
else:
plt.close()
#----------------------------------
plt.imshow(data_images[index])
plt.connect('key_press_event', toggle_images)
plt.show()
I would do this using ipywidgets within the IPython notebook. Here's an example:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interact
images = np.random.random((500, 14, 14))
def browse_images(images):
N = images.shape[0]
def view_image(i=0):
plt.imshow(images[i], cmap='gray', interpolation='nearest')
plt.title('Image {0}'.format(i))
interact(view_image, i=(0, N-1))
browse_images(images)
Edit: the result, in the notebook page, will look something like this:
You can press the left or right arrow to advance the slider and view the next image.
You can do a bit better in the notebook than using inline:
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interact
from IPython.display import display
images = np.random.random((500, 14, 14))
fig, ax = plt.subplots()
im = ax.imshow(images[0], cmap='gray', interpolation='nearest')
def browse_images(images):
N = images.shape[0]
def view_image(i=0):
im.set_data(images[i])
ax.set_title('Image {0}'.format(i))
fig.canvas.draw_idle()
interact(view_image, i=(0, N-1))
and then in the next cell
browse_images(images)
which will give you a pannable/zoom able figure. In mpl 1.5.0 you also get the pixel values under the cursor by default.
(I tested this on tmpnb.org)