自适应阈值错误:(-215:断言失败)函数“adaptiveThreshold”中的 src.type() == CV_8UC1

ash*_*ish 15 python opencv adaptive-threshold keras

我正在研究预训练的 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)
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)

帮助我解决问题。

Ahm*_*vli 18

该错误说明了解决方案:src.type() == CV_8UC1这意味着您需要将图像类型设置为uint8

因此,如果您重新定义img变量:

img = image.img_to_array(img, dtype='uint8')
Run Code Online (Sandbox Code Playgroud)

问题会解决,但我有一个问题。

为什么要定义下面的语句?

img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Run Code Online (Sandbox Code Playgroud)

你怎么知道load_img在时尚中加载图像BGR

cv2.imread我们知道opencv以时尚的方式加载图像BGR

该声明是错误的,因为以格式load_img加载图像RGB

因此,正确的说法是:

img_grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做:

img = image.load_img('15f8U.png', grayscale=True, target_size=(224, 224))
Run Code Online (Sandbox Code Playgroud)

正确代码:

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()
Run Code Online (Sandbox Code Playgroud)


Nic*_*ais 7

cv2.adaptive_threshold需要一个 dtype 的输入数组uint8

img_grey = img_grey.astype(np.uint8)

th3 = cv2.adaptiveThreshold(img_grey...
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用...`img2 = img.astype(np.uint8); 类型(img2) -&gt; numpy.ndarray; img2.dtype -&gt; dtype('uint8')` 但我仍然在函数 'adaptiveThreshold' 中得到 `src.type() == CV_8UC1`... (4认同)

小智 6

@bakuriu阈值仅适用于灰度图像,您需要首先将图像转换为灰度,然后将adaptiveThreshold



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)
Run Code Online (Sandbox Code Playgroud)