使用cv2.threshold函数时提示TypeError: Image data of dtype object cannot be converted to float

这篇博客主要介绍了在使用OpenCV进行图像处理时遇到的TypeError问题。在将灰度图像进行二值化处理时,由于忽视了`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')
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 的 `cv2.dnn.NMSBoxesRotated()` 函数,出现 `TypeError: Can't parse 'bboxes' wrong type` 错误,通常是因为传递给该函数的 `bboxes` 参数的类型或结构不符合预期。 ### 错误原因分析 `cv2.dnn.NMSBoxesRotated()` 用于处理旋转边界框(rotated bounding boxes),适用于检测倾斜目标(如文本检测等)。它要求 `bboxes` 是一个包含多个边界框的列表,每个边界框由 5 个浮点数表示:`[center_x, center_y, width, height, angle]`。如果传入的 `bboxes` 是 NumPy 数组、列表嵌套结构不正确,或者元素类型不是浮点型,则会引发类型错误[^1]。 ### 解决方案 确保 `bboxes` 的格式如下: ```python bboxes = [ [cx1, cy1, w1, h1, angle1], [cx2, cy2, w2, h2, angle2], ... ] ``` 其中每个子列表包含五个浮点数值,表示旋转框的中心坐标、宽高和角度。 如果 `bboxes` 是 NumPy 数组,可将其转换为 Python 列表: ```python bboxes_list = bboxes.tolist() # 将 numpy.ndarray 转换为 list indices = cv2.dnn.NMSBoxesRotated(bboxes_list, scores, score_threshold=0.5, nms_threshold=0.4) ``` ### 示例代码 以下是一个完整的后处理示例,展示如何正确使用 `cv2.dnn.NMSBoxesRotated()`: ```python import cv2 import numpy as np # 假设 detections 是模型输出的检测结果 detections = np.random.rand(10, 6) # 模拟输出,shape: (num_boxes, 6) bboxes = [] scores = [] for detection in detections: # 提取 [center_x, center_y, width, height, angle] bbox = detection[:5].tolist() score = detection[5] bboxes.append(bbox) scores.append(score) # 应用 NMS indices = cv2.dnn.NMSBoxesRotated(bboxes, scores, score_threshold=0.5, nms_threshold=0.4) # 获取保留的边界框索引 keep = indices.flatten() ``` ### 注意事项 - 确保 `bboxes` 和 `scores` 都是 Python 列表,且 `bboxes` 中的每个元素是长度为 5 的列表。 - 如果模型输出为 NumPy 数组,应使用 `.tolist()` 转换后再传入 `NMSBoxesRotated()`。 - `score_threshold` 控制置信度阈值,`nms_threshold` 控制重叠阈值[^1]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值