Skimage resize function returns black images - resize

I'm trying to resize some images that I've loaded using matplotlib's imread function.
An example:
plt.figure()
plt.imshow(imgs[0])
plt.colorbar()
plt.grid(False)
plt.show()
However, when I try to apply the resize function and then replot:
def rescale_image(img):
"""Rescale the jpg range of 0-255 to 0-1"""
img = resize(img, (100, 100), anti_aliasing=True)
return img /255
#imgs = [rescale_image(i) for i in imgs]
io = rescale_image(imgs[0])
plt.figure()
plt.imshow(io)
plt.colorbar()
plt.grid(False)
plt.show()
The result is:
Why?
UPDATE: The import statements:
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.image import imread
from skimage.transform import resize
imgs = [imread(p) for p in paths_list]# paths list is generated by glob.glob on the folder of images

Your image starts out with pixels in the range 0..1. When you resize it, you divide by 255, so the range is now 0..0.003 so it looks black.
Solution?
Change this line:
return img /255
to this:
return img

Related

matplotlib - show image color in hex format

I would like imshow display current image pixel value in hex format, by default it display pixel with decimal format.
for example, red color will be displayed as (255,0,0), I would like it to be (FF,00,00).
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import matplotlib.image as image
import matplotlib.patches as patches
import matplotlib
import cv2
matplotlib.use('tkagg')
img = cv2.imread("input.png",cv2.IMREAD_UNCHANGED)# cv2.IMREAD_UNCHANGED load alpha channel
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
fig,ax =plt.subplots(1,figsize=(15,15))
ax.imshow(img)
fig.tight_layout()
plt.show()
You could connect a function the motion_notify_event and update the toolbar. Here is a standalone example:
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib
def show_hex_coords(event):
text = ''
rgb = img_plot.get_cursor_data(event)
if rgb is not None:
r, g, b = rgb
text = f'x={event.xdata:.0f} y={event.ydata:.0f}\n{r:02X} {g:02X} {b:02X}'
# print( f'#{r:02X}{g:02X}{b:02X}')
fig.canvas.toolbar.set_message(text)
matplotlib.use('tkagg')
with cbook.get_sample_data('grace_hopper.jpg') as image_file:
img = plt.imread(image_file)
fig, ax = plt.subplots(1, figsize=(6, 6))
img_plot = ax.imshow(img)
fig.canvas.mpl_connect("motion_notify_event", show_hex_coords)
plt.show()

Embedding Matplotlib Animations in Python (google colab notebook)

I am trying to show a gif file in google's colab.research. I was able to save the file in the directory with the following path name /content/BrowniamMotion.gif but I don't know how to show this GIF in my notebook to present.
The code to generate the GIF so far, in case someone can manipulate it not to save the GIF but rather to animate it directly into the google colab file was,
# Other Brownian Motion
from math import *
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
fig = plt.figure(figsize=(8,6))
ax = plt.axes(projection='3d')
N=10
#val1 = 500
x=500*np.random.random(N)
y=500*np.random.random(N)
z=500*np.random.random(N)
def frame(w):
ax.clear()
global x,y,z
x=x+np.random.normal(loc=0.0,scale=50.0,size=10)
y=y+np.random.normal(loc=0.0,scale=50.0,size=10)
z=z+np.random.normal(loc=0.0,scale=50.0,size=10)
plt.title("Brownian Motion")
ax.set_xlabel('X(t)')
ax.set_xlim3d(-500.0,500.0)
ax.set_ylabel('Y(t)')
ax.set_ylim3d(-500.0,500.0)
ax.set_zlabel('Z(t)')
ax.set_zlim3d(-500.0,500.0)
plot=ax.scatter
3D(x, y, z, c='r')
return plot
anim = animation.FuncAnimation(fig, frame, frames=100, blit=False, repeat=True)
anim.save('BrowniamMotion.gif', writer = "pillow", fps=10 )
Sorry if this question is badly, stated. I am new to Python and using colab research.
For Colab it is easiest to use 'jshtml' to display matplotlib animation.
You need to set it up with
from matplotlib import rc
rc('animation', html='jshtml')
Then, just type your animation object. It will display itself
anim
Here's a workable colab of your code.
It has a slider where you can run back and forth at any point in time.
Using the same authors git repository seems like we have a solution to embed the plots as GIFs ( Save Matplotlib Animations as GIFs ).
#!apt install ffmpeg
#!brew install imagemagick
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML, Image # For GIF
rc('animation', html='html5')
np.random.seed(5)
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
def generateRandomLines(dt, N):
dX = np.sqrt(dt) * np.random.randn(1, N)
X = np.cumsum(dX, axis=1)
dY = np.sqrt(dt) * np.random.randn(1, N)
Y = np.cumsum(dY, axis=1)
lineData = np.vstack((X, Y))
return lineData
# Returns Line2D objects
def updateLines(num, dataLines, lines):
for u, v in zip(lines, dataLines):
u.set_data(v[0:2, :num])
return lines
N = 501 # Number of points
T = 1.0
dt = T/(N-1)
fig, ax = plt.subplots()
data = [generateRandomLines(dt, N)]
ax = plt.axes(xlim=(-2.0, 2.0), ylim=(-2.0, 2.0))
ax.set_xlabel('X(t)')
ax.set_ylabel('Y(t)')
ax.set_title('2D Discretized Brownian Paths')
## Create a list of line2D objects
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1])[0] for dat in data]
## Create the animation object
anim = animation.FuncAnimation(fig, updateLines, N+1, fargs=(data, lines), interval=30, repeat=True, blit=False)
plt.tight_layout()
plt.show()
# Save as GIF
anim.save('animationBrownianMotion2d.gif', writer='pillow', fps=60)
Image(url='animationBrownianMotion2d.gif')
## Uncomment to save the animation
#anim.save('brownian2d_1path.mp4', writer=writer)
Check this link out on using the HTML to get it to work http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/ .
I didn't embed a link but instead imbedded a HTML video that got it to work.
# Other Brownian Motion
from math import *
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
from IPython.display import HTML
fig = plt.figure(figsize=(8,6))
ax = plt.axes(projection='3d')
N=10
val1 = 600
x=val1*np.random.random(N)
y=val1*np.random.random(N)
z=val1*np.random.random(N)
def frame(w):
ax.clear()
global x,y,z
x=x+np.random.normal(loc=0.0,scale=50.0,size=10)
y=y+np.random.normal(loc=0.0,scale=50.0,size=10)
z=z+np.random.normal(loc=0.0,scale=50.0,size=10)
plt.title("Brownian Motion")
ax.set_xlabel('X(t)')
ax.set_xlim3d(-val1,val1)
ax.set_ylabel('Y(t)')
ax.set_ylim3d(-val1,val1)
ax.set_zlabel('Z(t)')
ax.set_zlim3d(-val1,val1)
plot=ax.scatter3D(x, y, z, c='r')
return plot
anim = animation.FuncAnimation(fig, frame, frames=100, blit=False, repeat=True)
anim.save('BrowniamMotion.gif', writer = "pillow", fps=10 )
HTML(anim.to_html5_video())
Essentially all we did hear was add,
from IPython.display import HTML to the premable and then add the line HTML(anim.to_html5_video()). This code then produces a video and saves the gif.

removing all white margins from plt.show() when trying do show an image

hello i'm trying to load an image and display it without having any margins
I could not find any solution to this and would appreciate assistance
code:
from matplotlib.image import imread
import matplotlib.pyplot as plt
path = 'some legal image path'
im = imread(path)
fig, ax = plt.subplots(figsize=plt.figaspect(im))
plt.axis('off')
fig.subplots_adjust(0, 0, 1, 1)
ax.imshow(im)
plt.show()
this still produces margins
enter image description here

How to resave image without borders in matplotlib

I am just want to show and then save the same image on plot but got borders.
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
fileName = "1.jpg"
image=mpimg.imread(fileName)
height, width = image.shape[:2]
my_dpi = 96 / 2
fg, ax = plt.subplots(1, figsize=(1080/my_dpi, 1920/my_dpi), dpi=my_dpi)
ax.set_ylim(height, 0)
ax.set_xlim(0, width)
ax.axis('off')
ax.imshow(image.astype(np.uint8))
plt.savefig("res.png")
Source image:
Result image after resaving:
How to remove the borders and make the result image be the same as original without borders?

Matplotlib - sequence is off when using plt.imshow()

I write a dog-classifier in a Jupyter notebook that, every time a dog is detected in an image, should show the image and print some text describing it. Somehow, the images are always displayed after all the text was printed, no matter in which order I put plt.imshow() and print(). Does anybody know why this is the case?
Thank you!
Here is my code-snippet:
for i in range (0, 1,1):
all_counter+=1
if dog_detector(dog_files_short[i]):
img = image.load_img(dog_files_short[i], target_size=(224, 224))
plt.show()
plt.imshow(img)
time.sleep(5)
print("That's a dog!!!!")
dog_counter+=1
print("______________")
else:
print("______________")
img = image.load_img(dog_files_short[i], target_size=(224, 224))
plt.show()
plt.imshow(img)
print("No Doggo up here :(")
print(ResNet50_predict_labels(dog_files_short[i]))
print("______________")
print((dog_counter/all_counter)*100, "% of the dog pictures are classified as dogs")
The output is like this:
It seems you are using Juypter notebook. This always shows any autogenerated output (like the matplotlib figures) last in the output.
You may use IPython.display.display to display the figures at the position of the output where they belong.
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display
images = [np.random.rayleigh((i+1)/8., size=(180, 200, 3)) for i in range(4)]
dog_detector = lambda x: np.random.choice([True,False])
dog_counter = 0
for i in range(len(images)):
if dog_detector(images[i]):
dog_counter+=1
fig, ax = plt.subplots(figsize=(3,2))
ax.imshow(images[i])
display(fig)
display("That's a dog!!!!")
display("______________")
else:
display("______________")
fig, ax = plt.subplots(figsize=(3,2))
ax.imshow(images[i])
display(fig)
display("No Doggo up here :(")
display("______________")
perc = (dog_counter/float(len(images)))*100
display("{}% of the dog pictures are classified as dogs".format(perc))
plt.close()
Output:
I tried this in my ipython notebook, if I first call plt.imshow(img) and plt.show() right after I get the image first and the text after.