首页 > 解决方案 > cv2.imread always returns NoneType python 3.6

问题描述

cv2.imread always returning NoneType.

I have the following code:

path = cv2.imread('D:/XXX/image.jpg')

The array returned is Nonetype

But when I use

path = cv2.imread('image.jpg')

I get the correct array. The problem only occurs when I use full path. I have tried backslashes and double slash as well, but it makes no difference. There are many similar questions asked before, I have havent got any suitable answer. The file path and file name are both correct.

I am using Python version 3.6 adn openCV version 3.4.3

Update I tried to get the file path using tkinter filedialog.askopenfilename. Yet unsuccessful.

标签: pythonpython-3.xopencv

解决方案


You are using it correctly but missed a parameter. calling cv2.imread(jpeg_file,0) yeild a ndtype array object

however, try this and make sure image file is not zero size.

img = cv2.imread(filename_name,0)

as the doc says

    Use the function cv2.imread() to read an image. The image should be in the working directory or a full path of image should be given.

Second argument is a flag which specifies the way image should be read.

cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.
cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
cv2.IMREAD_UNCHANGED : Loads image as such including alpha channel
Note Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively.
See the code below:

import numpy as np
import cv2

# Load an color image in grayscale
img = cv2.imread('messi5.jpg',0)

Cv2.imread usage


推荐阅读