沿着这条横线,R通道值变化折线图
检测结果:
上述图片相关代码:
import cv2
import matplotlib.pyplot as plt
import numpy as np
# 读取图像
img = cv2.imread('detect2.jpg')
# 指定横线的y坐标
y = 285 # 可以自行更改
# 获取图像的R通道数值
r_channel = img[y,:,2] # 注意,OpenCV用BGR格式读取图像,所以R通道的顺序为2
# 在图像上绘制选定的横线
img_with_line = cv2.line(img.copy(), (0, y), (img.shape[1] - 1, y), (0, 255, 0), 1) # 绘制绿色横线
# 创建一个和R通道相同长度的数组作为x坐标
x = np.arange(len(r_channel))
# 创建两个子图:第一个展示带有标记线的原图,第二个展示对应的R通道数值
fig, ax = plt.subplots(2, 1, figsize=(10,10))
# 显示带有横线的原图
ax[0].imshow(cv2.cvtColor(img_with_line, cv2.COLOR_BGR2RGB))
ax[0].set_title('Original Image with Specified Line')
# 显示R通道的数值
ax[1].plot(x, r_channel, color='red')
ax[1].set_xlabel('Pixel Position Along the Line')
ax[1].set_ylabel('Red Channel Value')
ax[1].set_title('R Channel Value Along the Specified Line')
plt.tight_layout()
plt.show()
以同样的方法,绘制GB通道的折线图
上图相关代码:
# Import necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
# Load image
img = cv2.imread('detect2.jpg')
# Specify y-coordinate for the line
y = 285
# Get the R, G and B channel values along the line
r_channel = img[y,:,2]
g_channel = img[y,:,1]
b_channel = img[y,:,0]
# Draw the specified line on a copy of the image
img_with_line = cv2.line(img.copy(), (0, y), (img.shape[1] - 1, y), (0, 255, 0), 1)
# Create an x-coordinate array of the same length as the channel data
x = np.arange(len(r_channel))
# Create the figure and axis for original image
fig1, ax1 = plt.subplots(figsize=(6,6))
# Plot the image with the specified line
ax1.imshow(cv2.cvtColor(img_with_line, cv2.COLOR_BGR2RGB))
ax1.set_title('Original Image with Specified Line')
plt.show()
# Create the figure and axes for the channel plots
fig2, ax2 = plt.subplots(3, 1, figsize=(6,10))
# Plot R channel value along the line
ax2[0].plot(x, r_channel, color='red')
ax2[0].set_xlabel('Pixel Position Along the Line')
ax2[0].set_ylabel('Red Channel Value')
ax2[0].set_title('R Channel Value Along the Specified Line')
# Plot G channel value along the line
ax2[1].plot(x, g_channel, color='green')
ax2[1].set_xlabel('Pixel Position Along the Line')
ax2[1].set_ylabel('Green Channel Value')
ax2[1].set_title('G Channel Value Along the Specified Line')
# Plot B channel value along the line
ax2[2].plot(x, b_channel, color='blue')
ax2[2].set_xlabel('Pixel Position Along the Line')
ax2[2].set_ylabel('Blue Channel Value')
ax2[2].set_title('B Channel Value Along the Specified Line')
# Set layout to tight and show the figure
plt.tight_layout()
plt.show()
注释:可以通过修改:fig1, ax1 = plt.subplots(figsize=(6,6)),调整输出图的大小