Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change numpy array into grayscale opencv image

How can I change numpy array into grayscale opencv image in python? After some processing I got an array with following atributes: max value is: 0.99999999988, min value is 8.269656407e-08 and type is: <type 'numpy.ndarray'>. I can show it as an image using cv2.imshow() function, but I can't pass it into cv2.AdaptiveTreshold() function because it has wrong type:

error: (-215) src.type() == CV_8UC1 in function cv::adaptiveThreshold

How can I convert this np.array to correct format?

like image 436
Leopoldo Avatar asked Jun 09 '14 16:06

Leopoldo


People also ask

How do I convert an image to grayscale in Python OpenCV?

Step 1: Import OpenCV. Step 2: Read the original image using imread(). Step 3: Convert to grayscale using cv2. cvtcolor() function.

How do I make an image grayscale in OpenCV?

So to convert the color image to grayscale we will be using cv2. imread("image-name. png",0) or you can also write cv2. IMREAD_GRAYSCALE in the place of 0 as it also denotes the same constant.


1 Answers

As the assertion states, adaptiveThreshold() requires a single-channeled 8-bit image.

Assuming your floating-point image ranges from 0 to 1, which appears to be the case, you can convert the image by multiplying by 255 and casting to np.uint8:

float_img = np.random.random((4,4))
im = np.array(float_img * 255, dtype = np.uint8)
threshed = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 0)
like image 99
Aurelius Avatar answered Sep 22 '22 14:09

Aurelius