前言
我不理解为啥opencv-python可视化一堆报错,同一个三通道图像,cv2.imshow()没有问题,cv2.circle()就一直有问题,搞了一晚,心态炸了!!!
cv2需要的图片矩阵(H, W, C)有两种
- 像素值范围为 [0,1] ------ 数据类型: float32
- 像素值范围为 [0,255] ------ 数据类型: uint8
源代码
for k, xys1 in enumerate(output_reproj['keyp_2d']):
new_image1 = target_dict['target_img'][k].numpy()
new_image1 = new_image1*255 / new_image1.max()
new_image1 = np.uint8(new_image1)
new_image1 = new_image1.transpose(1, 2, 0)
# cv2.imshow('222', new_image1)
# cv2.waitKey(5000)
# cv2.destroyAllWindows()
for i, x_y in enumerate(xys1):
print(111)
cv2.circle(new_image1, (int(x_y[0]), int(x_y[1])), 2, (0, 0, 255), -1)
说明:
target_dict[‘target_img’][k] 是(CHW)的 tensor,其数值范围是【0,1】类型是【torch.float32】
转换后的 new_image1 是 (HWC)的array,其数值范围是【0,255】类型是【np.uint8】
这里的new_image1直接 cv2.imshow 没有问题,但是 cv2.circle 就一直报下方的错误,排查不出原因
报错
cv2.circle(new_image1, (int(x_y[0]), int(x_y[1])), 2, (0, 0, 255), -1)
cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'circle'
> Overload resolution failed:
> - Layout of the output array img is incompatible with cv::Mat
> - Expected Ptr<cv::UMat> for argument 'img'
>
解决方法
加入两行代码即可,原因不知道,但可以跑通了
关键!!!!!
b, g, r = cv2.split(new_image1)
new_image1 = cv2.merge([r, g, b])
for k, xys1 in enumerate(output_reproj['keyp_2d']):
new_image1 = target_dict['target_img'][k].numpy()
new_image1 = new_image1*255 / new_image1.max()
new_image1 = np.uint8(new_image1)
new_image1 = new_image1.transpose(1, 2, 0)
'''修改后的'''
b, g, r = cv2.split(new_image1)
new_image1 = cv2.merge([r, g, b])
# cv2.imshow('222', new_image1)
# cv2.waitKey(5000)
# cv2.destroyAllWindows()
for i, x_y in enumerate(xys1):
print(111)
cv2.circle(new_image1, (int(x_y[0]), int(x_y[1])), 2, (0, 0, 255), -1)
更简单的方法,数值范围不用转到【0,255】,保留原本的【0,1】也可以
for k, xys1 in enumerate(output_reproj['keyp_2d']):
new_image1 = target_dict['target_img'][k].numpy()
new_image1 = new_image1.transpose(1, 2, 0)
b, g, r = cv2.split(new_image1)
new_image1 = cv2.merge([r, g, b])
# cv2.imshow('222', new_image1)
# cv2.waitKey(5000)
# cv2.destroyAllWindows()
for i, x_y in enumerate(xys1):
print(111)
cv2.circle(new_image1, (int(x_y[0]), int(x_y[1])), 2, (0, 0, 255), -1)
参考链接:CV2,Image,PIL图片读取,并且与Tensor相互转化并展示
吐槽一下
图像可视化还是 import matplotlib.pyplot as plt
用着舒服,tensor 和 array 都兼容,单通道和3通道也都可以,但是在图上画关键点还是用 import cv2
,plt 都没这些功能吗,很烦!