img_3 = cv2.imread(r'D:\Jupyter Notebook Files\cat.jpg')
img_gray = cv2.cvtColor(img_3, cv2.COLOR_BGR2GRAY)
img_threshold = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
plt.subplot(1,2,1),plt.title('img_gray'), plt.axis('off'),plt.imshow(img_gray)
plt.subplot(1,2,2),plt.title('img_threshold'), plt.axis('off'),plt.imshow(img_threshold, 'gray')
plt.show()
原输入如上图所示,此时提示:
TypeError: Image data of dtype object cannot be converted to float
这是因为cv2.threshold函数的返回值有两个,而上图代码只给了一个变量接收,正确写法如下:
img_3 = cv2.imread(r'D:\Jupyter Notebook Files\cat.jpg')
img_gray = cv2.cvtColor(img_3, cv2.COLOR_BGR2GRAY)
-, img_threshold = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
plt.subplot(1,2,1),plt.title('img_gray'), plt.axis('off'),plt.imshow(img_gray)
plt.subplot(1,2,2),plt.title('img_threshold'), plt.axis('off'),plt.imshow(img_threshold, 'gray')

这篇博客主要介绍了在使用OpenCV进行图像处理时遇到的TypeError问题。在将灰度图像进行二值化处理时,由于忽视了`cv2.threshold`函数的返回值是一个元组,导致了错误。正确的做法是为返回值提供两个变量来分别接收。通过修正代码,成功展示了原始图像和二值化后的图像,对于理解和解决类似问题有很好的指导作用。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



