自适应阈值错误:(-215:断言失败) 在函数'adaptiveThreshold'中,src.type() == CV_8UC1。

15

我正在使用预训练的vgg16模型进行工作,因此需要将图像文件的输入大小设置为(224,224,3)。

我正在处理的代码是:

from tensorflow.keras.preprocessing import image
import cv2
import matplotlib.pyplot as plt

img = image.load_img('abc.jpg',target_size=(224,224))
img = image.img_to_array(img)

print(img.shape)
## output : (224,224,3)
img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#plt.imshow(img_grey)

th3 = cv2.adaptiveThreshold(img_grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
plt.figure(figsize=(20,10))
plt.imshow(th3)
error                                     Traceback (most recent call last)
<ipython-input-88-2a8a27b965ed> in <module>
     17 #plt.imshow(img_grey)
     18 
---> 19 th3 = cv2.adaptiveThreshold(img_grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
     20 plt.figure(figsize=(20,10))
     21 plt.imshow(th3)

error: OpenCV(4.1.0) /io/opencv/modules/imgproc/src/thresh.cpp:1627: error: (-215:Assertion failed) src.type() == CV_8UC1 in function 'adaptiveThreshold'

帮我解决这个问题。

3个回答

18
错误提示的含义是: src.type() == CV_8UC1,这意味着你需要将图像类型设置为uint8参考资料 因此,如果重新定义img变量:
img = image.img_to_array(img, dtype='uint8')

问题将得到解决,但是我有一个问题。

为什么您要定义以下语句?

img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

你如何知道load_imgBGR方式加载图像?

我们知道opencv使用cv2.imreadBGR方式加载图像。

这个说法是错误的,因为load_img会以RGB格式加载图像,来源

因此,正确的说法应该是:

img_grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

或者你可以这样做:

img = image.load_img('15f8U.png', grayscale=True, target_size=(224, 224))

正确的代码:

from keras.preprocessing import image
import cv2
import matplotlib.pyplot as plt

img = image.load_img('15f8U.png', grayscale=True, target_size=(224, 224))
img = image.img_to_array(img, dtype='uint8')

print(img.shape)
## output : (224,224,3)
#plt.imshow(img_grey)

th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
plt.figure(figsize=(20,10))
plt.imshow(th3, cmap="gray")
plt.show()

7

cv2.adaptive_threshold需要一个数据类型为uint8的输入数组:

img_grey = img_grey.astype(np.uint8)

th3 = cv2.adaptiveThreshold(img_grey...

4
这对我没用......img2 = img.astype(np.uint8); type(img2) -> numpy.ndarray; img2.dtype -> dtype('uint8'),但是我仍然得到了adaptiveThreshold函数返回的src.type() == CV_8UC1错误提示。 - Bakuriu

6

@bakuriu 阈值处理仅适用于灰度图像,您需要先将图像转换为灰度图像,然后再使用自适应阈值算法。



img = image.img_to_array(img2, dtype='uint8')
img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th3 = cv2.adaptiveThreshold(img_grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接