Read image grayscale opencv 3.0.0-dev

PythonOpencvGrayscale

Python Problem Overview


I am trying to read images directly as black and white.

I recently updated my OpenCv version to 3.0.0-dev, and the code that I used before does not work anymore.

   img = cv2.imread(f, cv2.CV_LOAD_IMAGE_GRAYSCALE)

works fine for 2.4 but does not work for the new version, as there is no field CV_LOAD_IMAGE_GRAYSCALE.

Any suggestions?

Note: I know that cv2.imread(f,0) will work, but I do not like having unnamed constants in my code. Thanks!

Python Solutions


Solution 1 - Python

The flag has been renamed to cv2.IMREAD_GRAYSCALE. Generally speaking, flags now have names prefixed in a manner that relates to the function to which they refer. (e.g. imread flags start with IMREAD_, cvtColor flags start with COLOR_, etc.)

Solution 2 - Python

Try this it works for me

import cv2
im_gray = cv2.imread('gray_image.png', cv2.IMREAD_GRAYSCALE)
thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('blackwhite.png', im_bw)

Solution 3 - Python

Try this, it works for me everytime

import cv2
gray_img = cv2.imread('img.png', 0)
cv2.imshow(gray_img)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionelaRoscaView Question on Stackoverflow
Solution 1 - PythonAureliusView Answer on Stackoverflow
Solution 2 - PythonJibin MathewView Answer on Stackoverflow
Solution 3 - PythonSarthak VajpayeeView Answer on Stackoverflow