OpenCV直方图计算与显示:解决Matplotlib绘图错误
OpenCV直方图计算与显示:解决Matplotlib绘图错误
在使用OpenCV和Matplotlib处理图像直方图时,您可能会遇到一些常见的错误。本文将介绍如何解决这些错误,并提供可运行且优化的代码。
问题分析
在使用 plt.subplot()、plt.hist() 和 plt.imshow() 函数时,经常会出现以下错误:
-
MatplotlibDeprecationWarning: Auto-removal of overlapping axes is deprecated since 3.6 and will be removed two minor releases later; explicitly call ax.remove() as needed.
- 出现原因:使用
plt.subplot()创建子图时出现重叠。 - 解决方法:使用
fig, axs = plt.subplots()创建图形和子图的网格,然后使用axs[row, col].plot()分别绘制每个子图。
- 出现原因:使用
-
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
- 出现原因:
plt.hist()函数返回的hist是一个嵌套列表,而不是 NumPy 数组。 - 解决方法:使用
np.array(hist)将其转换为 NumPy 数组。
- 出现原因:
-
TypeError: Image data of dtype object cannot be converted to float
- 出现原因:
plt.imshow()函数需要浮点类型的图像数据,但输入数据类型不正确。 - 解决方法:使用
.astype(np.uint8)将图像数据转换为uint8类型。
- 出现原因:
解决方案
以下代码展示了如何解决上述错误:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取图像
img = cv2.imread('C:/Users/LENOVO/Desktop/c.jpg')
# 将图像转换为灰度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 计算彩色图像的直方图
hist1, bins, _ = plt.hist(img.ravel(), 256, [0, 256])
hist1 = np.array(hist1)
hist2 = cv2.calcHist([img], [0], None, [256], [0, 255])
# 显示图像和直方图
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
axs[0, 0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # 将BGR转换为RGB
axs[0, 0].set_title('彩色图像')
axs[0, 1].plot(hist1)
axs[0, 1].set_title('彩色图像直方图')
axs[1, 0].imshow(gray, cmap='gray')
axs[1, 0].set_title('灰度图像')
axs[1, 1].plot(hist2)
axs[1, 1].set_title('灰度图像直方图')
plt.tight_layout()
plt.show()
代码解释
- 使用
cv2.imread()函数读取图像。 - 使用
cv2.cvtColor()函数将图像转换为灰度。 - 使用
plt.hist()函数计算彩色图像的直方图,并将结果存储在hist1中。 - 使用
cv2.calcHist()函数计算灰度图像的直方图,并将结果存储在hist2中。 - 使用
fig, axs = plt.subplots()创建一个包含 2 行 2 列子图的图形窗口。 - 使用
axs[row, col].imshow()函数在相应的子图中显示图像。 - 使用
axs[row, col].plot()函数在相应的子图中绘制直方图。 - 使用
plt.tight_layout()函数自动调整子图参数,以避免重叠。 - 使用
plt.show()函数显示图形。
通过以上步骤,您就可以成功解决使用 OpenCV 和 Matplotlib 处理图像直方图时遇到的常见错误。
原文地址: https://www.cveoy.top/t/topic/jtgg 著作权归作者所有。请勿转载和采集!