首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >自适应阈值错误:(-215:断言失败) src.type() == CV_8UC1 in function 'adaptiveThreshold‘

自适应阈值错误:(-215:断言失败) src.type() == CV_8UC1 in function 'adaptiveThreshold‘
EN

Stack Overflow用户
提问于 2021-01-14 19:27:57
回答 2查看 6.6K关注 0票数 1

我在预训练的vgg16模型上工作,为此,我需要有图像文件的输入大小为(224,224,3)。

我正在编写的代码是:

代码语言:javascript
运行
复制
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)
代码语言:javascript
运行
复制
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'

帮我解决这个问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-01-14 19:57:53

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

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

代码语言:javascript
运行
复制
img = image.img_to_array(img, dtype='uint8')

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

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

代码语言:javascript
运行
复制
img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

你怎么知道load_img会以BGR的方式加载图片?

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

该语句是错误的,因为load_imgRGB格式source加载图像

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

代码语言:javascript
运行
复制
img_grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

或者你可以这样做:

代码语言:javascript
运行
复制
img = image.load_img('15f8U.png', grayscale=True, target_size=(224, 224))

正确的代码:

代码语言:javascript
运行
复制
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()
票数 4
EN

Stack Overflow用户

发布于 2021-01-14 19:55:34

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

代码语言:javascript
运行
复制
img_grey = img_grey.astype(np.uint8)

th3 = cv2.adaptiveThreshold(img_grey...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65718126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档