0

This is the code that I currently have. I want to avoid writing an image then loading it again and then copying it. Why isn't my code in the second part working?

import cv2

load_imaged = cv2.imread("image.png", 0)

# Apply GaussianBlur to reduce image noise if it is required
otsu_threshold, otsu_result = cv2.threshold(
    load_imaged, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU, )
# Optimal threshold value is determined automatically.

# Visualize the image after the Otsu's method application
cv2.imwrite("otsu.png", otsu_result)

hole_image = cv2.imread("otsu.png")

# copy image
img = hole_image.copy()
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cv2.imshow("Image", imgray)
cv2.waitKey()
cv2.destroyAllWindows()

and I'm trying to reference the image like this (in line 9) but it's returning an error.

Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1

import cv2

load_imaged = cv2.imread("image.png", 0)

# Apply GaussianBlur to reduce image noise if it is required
otsu_threshold, otsu_result = cv2.threshold(
    load_imaged, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU, )
# copy image
img = otsu_result.copy()
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cv2.imshow("Image", imgray)
cv2.waitKey()
cv2.destroyAllWindows()

Any help is appreciated

Vincent Liow
  • 101
  • 1
  • 6

1 Answers1

2

You are trying to convert an gray-scale image into gray image.

Remove imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) line and you will get the result.

Ahmet
  • 7,527
  • 3
  • 23
  • 47
  • That was a simple fix! Of course. I didn't think it would have been a problem. Thank you for the quick reply. – Vincent Liow Dec 21 '20 at 08:48
  • You're welcome. Make sure to check the shape of the image. (if gray-scale shape is `width, height`, if rgb `width, height, 3`). Also check this [answer](https://stackoverflow.com/questions/23660929/how-to-check-whether-a-jpeg-image-is-color-or-gray-scale-using-only-python-stdli) – Ahmet Dec 21 '20 at 08:52