Using cv2.imread: "<built-in function imread> returned NULL without setting an error", 好像打不开图片,取不到数据

Using cv2.imread: "<built-in function imread> returned NULL without setting an error", as if it can't open the picture or get the data

这是我的代码中出现问题的部分。它应该计算图片中绿色像素的数量:

img = Image.open('path.tif')

BLACK_MIN = np.array([0, 20, 20], np.uint8)

BLACK_MAX = np.array([120, 255, 255], np.uint8)

imgg = cv2.imread(img, 1)

dst = cv2.inRange(imgg, BLACK_MIN, BLACK_MAX)

no_black = cv2.countNonZero(dst)

print('The number of black pixels is: ' + str(no_black))

您正在将 PIL 图像传递给 imread,但它需要一个文件路径(https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imread#Mat%20imread(const%20string&%20filename,%20int%20flags)

你应该使用:

imgg = cv2.imread('path.tif', 1)

图像已经使用 PIL.Now 读取,img 是数组格式,因此您无法读取它 again.Read 您的文件的任何一种格式,无论是 pil 还是 cv2

BLACK_MIN = np.array([0, 20, 20], np.uint8)

BLACK_MAX = np.array([120, 255, 255], np.uint8)

imgg = cv2.imread('path.tif', 1)

dst = cv2.inRange(imgg, BLACK_MIN, BLACK_MAX)

no_black = cv2.countNonZero(dst)

print('The number of black pixels is: ' + str(no_black))