本文主要是介绍When the input arrays in add/subtract/multiply/divide functions have different types, the output arr,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
python 中使用cv2出现的错误。
背景:自己谢了一个热力图可视化的轮子,代码如下:
def intensity_heatmap(background_img, intensity_map, blue_mask_weight=0.3, heat_map_weight=0.5):""":param background_img: 背景图 shape=[H,W,C]:param intensity_map: 损失强度图 shape=[H,W,C]:param blue_mask_weight::param heat_map_weight::return:"""assert background_img.ndim == 3assert intensity_map.ndim == 2 or intensity_map.ndim == 3assert background_img.shape[0:2] == intensity_map.shape[0:2]background_img_norm = ((background_img - background_img.min()) / (background_img.max() - background_img.min())* 255).astype(np.uint8)intensity_map_norm = ((intensity_map - intensity_map.min()) / (intensity_map.max() - intensity_map.min())* 255).astype(np.uint8)# 背景图需要加一个蓝色掩码,以更好的显示热力图blue_mask = cv2.rectangle(background_img.copy(), (0, 0), background_img.shape[0:2], (0, 0, 256), -1)heatmap_base = cv2.addWeighted(blue_mask, blue_mask_weight, background_img_norm, 1 - blue_mask_weight, 0,dtype=cv2.CV_8U)# heatmap_base = cv2.addWeighted(blue_mask, blue_mask_weight, background_img_norm, 1 - blue_mask_weight, 0,# dtype=cv2.CV_32F)# 获取热力图hotmap_blue = np.array(cv2.applyColorMap(intensity_map_norm, cv2.COLORMAP_HOT)) # 是蓝色的3通道heatmaphotmap_red = cv2.cvtColor(hotmap_blue, cv2.COLOR_RGB2BGR) # 由蓝色heatmap转为红色heatmapintensity_hotmap_img = cv2.addWeighted(hotmap_red, heat_map_weight, heatmap_base, 1 - heat_map_weight, 0)return intensity_hotmap_img
但是有时候经常出现这个错误(真的是不只一次,很烦,每一次都要上网查一下...):
Traceback (most recent call last):File "draw_bin_on_img.py", line 52, in <module>img2 = cv2.addWeighted(img,0.01,img0,0.99,0)
cv2.error: OpenCV(4.1.2) /io/opencv/modules/core/src/arithm.cpp:687: error: (-5:Bad argument) When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified in function 'arithm_op‘
错误的原因:就是cv2.addWeighted的两幅图像的数据格式不一样。
解决方法:
具体的修正方法就是通过对数据格式的设置,强迫使两个图像的数据格式一致。
修改方式1:一些博客的解决方法是:
img2 = cv2.addWeighted(img,0.01,img0,0.99,0, CV_32F)
但是这种方法会报错:
Traceback (most recent call last):File "draw_bin_on_img.py", line 51, in <module>img2 = cv2.addWeighted(img,0.01,img0,0.99,0, CV_32F)
NameError: name 'CV_32F' is not defined
修改方式2:进一步的修改方法是:
img2 = cv2.addWeighted(img,0.01,img0,0.99,0, dtype = cv2.CV_32F)
此时需要注意的问题是:我们设置的dtype=cv2.CV_32F。 cv2可是修改数据格式,但是并没有对数据进行归一化,所以,如果是的像素取值是[0,255]的话,此时显示的图像会是空白图。
修改方式3:
img2 = cv2.addWeighted(img,0.01,img0,0.99,0, dtype = cv2.CV_32F)
如果两个源图像的像素取值范围是[0,255],应该设置dtype=cv2.CV_8U,
如果两个源图像的像素取值范围是[0, 1],应该设置dtype=cv2.CV_32F
参考:https://blog.csdn.net/qq_35250841/article/details/108320967
这篇关于When the input arrays in add/subtract/multiply/divide functions have different types, the output arr的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!