65

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!

elaRosca
  • 3,083
  • 4
  • 21
  • 22

3 Answers3

98

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.)

Aurelius
  • 11,111
  • 3
  • 52
  • 69
  • 1
    Awesome. Thanks for the explanation, will probably help in the future as well. – elaRosca Apr 28 '14 at 15:39
  • 1
    The documentation should be updated accordingly: http://docs.opencv.org/trunk/modules/imgcodecs/doc/reading_and_writing_images.html?highlight=imread#Mat imread(const String& filename, int flags) – Eduard Feicho Feb 04 '15 at 18:56
  • @EduardFeicho 's Link is down, here is a current one https://docs.opencv.org/4.6.0/d8/d6a/group__imgcodecs__flags.html#ga61d9b0126a3e57d9277ac48327799c80 – Nivatius Oct 04 '22 at 06:25
33

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)
Jibin Mathew
  • 4,816
  • 4
  • 40
  • 68
1

Try this, it works for me everytime

import cv2
gray_img = cv2.imread('img.png', 0)
cv2.imshow(gray_img)
  • 7
    My guess is downvote(s) because OP wrote "I know that cv2.imread(f,0) will work, but I do not like having unnamed constants in my code." – eric Jul 06 '19 at 14:07
  • And opencv docs use such line a lot https://docs.opencv.org/4.x/d7/d4d/tutorial_py_thresholding.html – Eloy Pérez Torres Jul 28 '22 at 15:17