from skimage.io import imread, imshow
from skimage.filters import threshold_otsu
imgtest = imread('image.tif')
img_threshold = threshold_otsu(imgtest)
imshow(img_threshold)
returns
Traceback (most recent call last):
File "<input>", line 8, in <module>
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/io/_io.py", line 159, in imshow
return call_plugin('imshow', arr, plugin=plugin, **plugin_args)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/io/manage_plugins.py", line 209, in call_plugin
return func(*args, **kwargs)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/io/_plugins/matplotlib_plugin.py", line 158, in imshow
ax_im = ax.imshow(image, **kwargs)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/matplotlib/__init__.py", line 1447, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 5523, in imshow
im.set_data(X)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/matplotlib/image.py", line 711, in set_data
raise TypeError("Invalid shape {} for image data"
TypeError: Invalid shape () for image data
and also
img_threshold2 = akt1 > 100
imshow(img_threshold2)
returns another error:
Traceback (most recent call last):
File "<input>", line 2, in <module>
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/io/_io.py", line 159, in imshow
return call_plugin('imshow', arr, plugin=plugin, **plugin_args)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/io/manage_plugins.py", line 209, in call_plugin
return func(*args, **kwargs)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/io/_plugins/matplotlib_plugin.py", line 150, in imshow
lo, hi, cmap = _get_display_range(image)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/io/_plugins/matplotlib_plugin.py", line 97, in _get_display_range
ip = _get_image_properties(image)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/io/_plugins/matplotlib_plugin.py", line 55, in _get_image_properties
is_low_contrast(image))
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/skimage/exposure/exposure.py", line 637, in is_low_contrast
limits = np.percentile(image, [lower_percentile, upper_percentile])
File "<__array_function__ internals>", line 5, in percentile
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/numpy/lib/function_base.py", line 3818, in percentile
return _quantile_unchecked(
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/numpy/lib/function_base.py", line 3937, in _quantile_unchecked
r, k = _ureduce(a, func=_quantile_ureduce_func, q=q, axis=axis, out=out,
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/numpy/lib/function_base.py", line 3515, in _ureduce
r = func(a, **kwargs)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/numpy/lib/function_base.py", line 4064, in _quantile_ureduce_func
r = _lerp(x_below, x_above, weights_above, out=out)
File "/Users/Simo/opt/anaconda3/envs/segmentation/lib/python3.8/site-packages/numpy/lib/function_base.py", line 3961, in _lerp
diff_b_a = subtract(b, a)
TypeError: numpy boolean subtract, the `-` operator, is not supported, use the bitwise_xor, the `^` operator, or the logical_xor function instead.
as well.
I'm quite new to Python, so after reinstalling the packages mentioned in the errors (numpy, skimage) I exhausted my knowledge..
I'm using a conda environment & PyCharm, if it's useful to know.
Cheers
P.S. I'm on macOS Catalina
threshold_otsu works properly on gray images.
I'm loading a color image and converting to gray for the example, if you already have gray image you can ignore that step.
from skimage.io import imread, imshow
from skimage.filters import threshold_otsu
from skimage.color import rgb2gray
imgtest = imread('00000001.jpg') # load my rgb image
gray = rgb2gray(imgtest) # convert to gray
img_threshold = threshold_otsu(gray) # apply thresholding
print(img_threshold) # 0.369140625 this is a number can't use imshow over this
binary = gray > img_threshold # converting to binary based on threshold -- this can be passed to imshow
imshow(binary) # image will be displayed now.!
I think this answer can fix the problem, as it's what I used to handle it.
threshold_otsu expects an input image in grayscale, and it returns a threshould, a single scalar value. All pixels whose value >= threshold are assumed to be foreground.
import matplotlib.pyplot as plt
from skimage.io import imread, imshow
from skimage.filters import threshold_otsu
imgurl = 'https://i.picsum.photos/id/732/200/300.jpg?grayscale&hmac=ZeormnImNpZEXzeLNhI0BCcadwMVGAwJLPRh_Sl-7Wg'
img = imread(imgurl) # Input image mast be grayscale
threshold = threshold_otsu(img) # 132
binary = threshold <= img # [[True True ...],..., [False True...]]
# Pixel assumed to be forground where value >= threshould, otherwise background
imshow(binary)
# Btw, You can show images side by side by matplotlib.plt
import matplotlib.pyplot as plt
f, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(img, cmap='gray')
ax1.imshow(binary, cmap='gray')
plt.show() # attached below
threshold_otsu (Scikit-image)
Otsu method (Wikipedia)
Related
I am trying to program a code that accepts an image,rescales it to a smaller values,uses border detection and gives out an ASCII art.
But the problem arises with the part where im unable to retrieve the rescaled imagge.
here is the code:
from matplotlib import image
from matplotlib import pyplot
# load image as pixel array
image = image.imread(r'C:\Users\lavni\OneDrive\Desktop\asci.png')
# summarize shape of the pixel array
print(image.dtype)
print(image.shape)
image=image.resize((52,int((image.shape[1]*52)/image.shape[0])))
# display the array of pixels as an image
pyplot.imshow(image)
pyplot.show()
and i get the error:
(648, 1152, 3)
Traceback (most recent call last):
File "C:/Users/lavni/AppData/Local/Programs/Python/Python38-32/ASCII.py", line 11, in <module>
pyplot.imshow(image)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\pyplot.py", line 2645, in imshow
__ret = gca().imshow(
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\__init__.py", line 1565, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\cbook\deprecation.py", line 358, in wrapper
return func(*args, **kwargs)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\cbook\deprecation.py", line 358, in wrapper
return func(*args, **kwargs)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\axes\_axes.py", line 5626, in imshow
im.set_data(X)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\image.py", line 693, in set_data
raise TypeError("Image data of dtype {} cannot be converted to "
TypeError: Image data of dtype object cannot be converted to float
Use openCV library
pip install opencv-python
Code:
import cv2
img2 = cv2.imread(filename)
resized = cv2.resize(img2, dsize=(28,28), interpolation=cv2.INTER_CUBIC)
I want to load .npy file in Anaconda3 Prompt.
My code is:
import numpy as np
from matplotlib import pyplot as plt
img_array = np.load.('delta1.npy',encoding = 'latin1')
plt.imshow(img_array,cmap = "gray")
plt.show()
I'm getting the following error:
Traceback (most recent call last):
File "check1.py", line 12, in <module>
plt.imshow(img_array,cmap = "gray")
File "C:\Users\Mohammed\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2699, in imshow
None else {}), **kwargs)
File "C:\Users\Mohammed\Anaconda3\lib\site-packages\matplotlib\__init__.py", line 1810, in inner
return func(ax, *args, **kwargs)
File "C:\Users\Mohammed\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 5494, in imshow
im.set_data(X)
File "C:\Users\Mohammed\Anaconda3\lib\site-packages\matplotlib\image.py", line 634, in set_data
raise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float
I want to know exactly what mistake I did that I got the error above.Can anyone help me with this?
You need to convert your numpy array to an Image format to be able to plt.imshow() it.
from PIL import Image
img = Image.fromarray(img_array)
plt.imshow(img, cmap = "gray")
source
I have the following jpeg as a bytecode string:
jpg = 'b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xfe\x00>CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), default quality\n\xff\xdb\x00C\x00\x08\x06\x06\x07
I want to dispaly this for image processing with openCV.
I tried:
import numpy as np
from matplotlib import pyplot as plt
nparr = np.fromstring(jpg, np.uint8)
plt.imshow(nparr, cmap='gray')
plt.show()
I'm getting:
File "....\lib\site-packages\matplotlib\pyplot.py", line 3205, in imshow
**kwargs)
File "....\lib\site-packages\matplotlib\__init__.py", line 1855, in inner
return func(ax, *args, **kwargs)
File "....\lib\site-packages\matplotlib\axes\_axes.py", line 5487, in imshow
im.set_data(X)
File "....\lib\site-packages\matplotlib\image.py", line 653, in set_data
raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data
How can I get this working?
I am trying to read a raw image file, but the stored image array seems to be one dimensional. Not sure how to read a raw file and plot it. Any help would be appreciated
Link to image TestImage1c.raw
from scipy import misc
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
import math
A = np.fromfile("TestImage1c.raw", dtype='int16', sep="")
print("A.shape: %d", A.shape)
print("A: ", A)
img_gray = np.dot(A[..., :3], [0.30, 0.59, 0.11])
print("img_gray :", img_gray)
print("img_gray shape: ", img_gray.shape)
print("img_gray size: ", img_gray.size)
plt.imshow(img_gray, cmap="gray")
plt.show()
OUTPUT:
D:\Python36\python.exe D:/PycharmProjects/First/readrawimage.py
A.shape: %d (1143072,)
A: [-27746 -24987 26514 ..., 28808 -31403 18031]
img_gray : -20149.59
img_gray shape: ()
img_gray size: 1
Traceback (most recent call last):
File "D:/PycharmProjects/First/readrawimage.py", line 33, in <module>
plt.imshow(img_gray, cmap="gray")
File "D:\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in
imshow
**kwargs)
File "D:\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in
inner
return func(ax, *args, **kwargs)
File "D:\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194,
in imshow
im.set_data(X)
File "D:\Python36\lib\site-packages\matplotlib\image.py", line 604, in
set_data
raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data
Process finished with exit code 1
I found that RAW file is interleaved with RGB value an is one dimensional array
R(0,0) G(0,0) B(0,0)
R(0,1) G(0,1) B(0,1)
.......
A = np.fromfile("TestImage2c.raw", dtype='int8', sep="")
A = np.reshape(A, (756, 1008, 3))
img_gray = np.dot(A[..., :3], [0.30, 0.59, 0.11])
plt.imshow(img_gray, cmap="gray")
plt.show()
I started getting the image now.
Thank you all for response.
I am trying to save a gray scale image (256,256,1) and show it in the output.
im = data.astype(np.uint8)
print im.shape
im = np.transpose(im, (2,1,0))
print im.shape
im.show()
However, I am getting the following error:
(256, 256, 1)
Traceback (most recent call last):
File "lmdb_reader.py", line 37, in <module>
plt.imshow(im)
File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3029, in imshow
**kwargs)
File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/__init__.py", line 1819, in inner
return func(ax, *args, **kwargs)
File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 4922, in imshow
im.set_data(X)
File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/image.py", line 453, in set_data
raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data
Note that im.show() does not exist, but it might just be a typo in the question.
The real problem is the following:
Matplotlib's pyplot.imshow can plot images of dimension (N,M) (grayscale) or (N,M,3) (rgb color). Your image is (N,M,1); we therefore need to get rid of the last dimension.
import matplotlib.pyplot as plt
import numpy as np
#create data of shape (256,256,1)
data = np.random.rand(256,256,1)*255
im = data.astype(np.uint8)
print im.shape # prints (256L, 256L, 1L)
# (256,256,1) cannot be plotted, therefore
# we need to get rid of the last dimension:
im = im[:,:,0]
print im.shape # (256L, 256L)
# now the image can be plotted
plt.imshow(im, cmap="gray")
plt.show()
You need to specify the colormap before calling matplotlib.pyplot.show().
By default the function expects RGB images when you pass a 3D array.
Example:
im = np.squeeze(im)
plt.imshow(im,cmap='gray')
plt.show()