0

I used the link below for thresholding of my images. https://github.com/subokita/Sandbox/blob/master/otsu.py but my images was grayscale and I didn't as same as the link. now I want to use the function otsu2 or otsu1

img=cv2.imread('E:/tilpixs2/23_1050_450_5.0X/til1.G.png')

rows,cols,channelsNo=shape(img)

# create 256 bins histogram
hist = histogram(img, 256)[0] 

# apply the otsu thresholding
thresh=otsu2(hist,rows*cols)
img2=img>=thresh

plt.imsave("E:/tilpixs2/img2.png", img2)

img2.dtype  #it is boolean 

To convert img2 to uint8, I did some convertions. Some of them are here"

img2.dtype='uint8'

or

img4=img2.astype(uint8)

or

npyage = np.array(img2)
img3=img2.np.uint8

But when I check the image when saved, the bit depths in properties of image is 32. I'm totally confused, What should I do? what does 32 in bit depth means? I want an image of 8 bit int

This is the properties of image

diana
  • 1
  • 2
  • I can't reproduce your error. As long as you specify the `dtype` of your image, then save with `plt.imsave` it should respect the bit depth that it was saved at. Also, since you're using OpenCV you should use `cv2.imwrite` instead. It's usually not a good idea to mix packages when dealing with image I/O. – rayryeng Mar 08 '21 at 16:41
  • I used cv2.imwrite too. But the image saved with 32 bit depth again. – diana Mar 09 '21 at 08:18
  • This is a classic case of PEBKAC. Voting to close as your error is not reproducible. – rayryeng Mar 09 '21 at 13:24

1 Answers1

0

Assuming that plt is an object reference to Matplotlib.pyplot, the module doesn't respect color depth for it's imsave call. OpenCV's imsave will respect the datatype. See the documentation for pyplot's image save call here: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imsave.html

img = cv2.imread('E:/tilpixs2/23_1050_450_5.0X/til1.G.png')

rows, cols, channelsNo = shape(img)

# create 256 bins histogram
hist = histogram(img, 256)[0]

# apply the otsu thresholding
thresh = otsu2(hist, rows * cols)
img2 = img >= thresh

img3 = img2.astype(uint8)

# Choose one of the options below depending on required format

# Save all 3 channels as a 24bpp grayscale image
cv2.imwrite("E:/tilpixs2/img2.png", img3)

# Save a single channel as a 8bpp grayscale image
cv2.imwrite("E:/tilpixs2/img2.png", img3[:,:,1])
Abstract
  • 985
  • 2
  • 8
  • 18
  • Thank you,but I checked it before, the cv2.imwrite doesn't save with 8 bit depth – diana Mar 09 '21 at 05:59
  • Yes, OpenCV *does* save with 8-bit depth. – rayryeng Mar 09 '21 at 07:20
  • @diana Are you referring to the image format reading 24bpp instead of 8bpp? It's 8 bit depth, but the 24bpp you're seeing is a 3-channel grayscale each with the same 8bit value in each channel. See my edits above and choose the save function that you're interested in. – Abstract Mar 09 '21 at 16:46
  • Thank you @Jon, I will check it in my codes. – diana Mar 11 '21 at 14:03