OpenCV 绘制直方图时 cv2.line() 函数报错:(-5:Bad argument) 解决方法
OpenCV 绘制直方图时 cv2.line() 函数报错:(-5:Bad argument) 解决方法
在使用 OpenCV 的 cv2.line() 函数绘制直方图时,你可能会遇到类似这样的错误信息:
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'line'
原因分析
出现这个错误的原因是在调用 cv2.line() 函数绘制直线时,传递的参数类型不正确。cv2.line() 函数要求传入的坐标值必须是整数,而代码中可能传递了浮点数。
解决方法
将绘制直方图时用到的像素值从浮点数转换为整数即可解决问题。
错误代码示例:
import cv2
from matplotlib import pyplot as plt
import numpy as np
img = cv2.imread('c.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
hist = cv2.calcHist([gray],[0],None,[256],[0,256])
hist = np.squeeze(hist)
hist_img = np.zeros((256,256,3),dtype=np.uint8)
cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)
for i in range(256):
# 错误:传递了浮点数作为坐标值
cv2.line(hist_img, (i, 255), (i, 255 - hist[i]), (255, 255, 255))
plt.subplot(221), plt.imshow(img, 'gray'), plt.title('Image1')
plt.subplot(222), plt.hist(img.ravel(), 256, [0, 256]),
plt.title('Histogram'), plt.xlim([0, 256])
plt.subplot(223),plt.imshow(hist_img),plt.title('Histogram_opencv')
plt.show()
修改后代码:
import cv2
from matplotlib import pyplot as plt
import numpy as np
img = cv2.imread('c.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
hist = cv2.calcHist([gray],[0],None,[256],[0,256])
hist = np.squeeze(hist)
hist_img = np.zeros((256,256,3),dtype=np.uint8)
cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)
for i in range(256):
# 正确:将 hist[i] 转换为整数
cv2.line(hist_img, (i, 255), (i, 255 - int(hist[i])), (255, 255, 255))
plt.subplot(221), plt.imshow(img, 'gray'), plt.title('Image1')
plt.subplot(222), plt.hist(img.ravel(), 256, [0, 256]),
plt.title('Histogram'), plt.xlim([0, 256])
plt.subplot(223),plt.imshow(hist_img),plt.title('Histogram_opencv')
plt.show()
通过将 hist[i] 转换为整数,即可解决 cv2.line() 函数报错的问题,正常绘制直方图。
原文地址: https://www.cveoy.top/t/topic/jtfS 著作权归作者所有。请勿转载和采集!