OpenCV中是否有一个开箱即用的函数,可以沿着线从图像中提取强度轮廓,就像MATLAB中的improfile
函数一样?
haidimingzhushiwo 回答:如何沿线提取强度分布图?
这是一个小型的交互式Python应用程序,用于模仿MATLAB的improfile
。
图像已加载,并显示在OpenCV窗口中。记录鼠标按键的向下和向上事件以获取生产线的起点和终点。图像中显示了线条(白色),附加的Matplotlib窗口中显示了相应的RGB强度配置文件。可以通过在OpenCV窗口中按c
键退出无限循环。
外观如下:
然后是代码:
import cv2
from matplotlib import pyplot as plt
import numpy as np
from skimage import draw
# Actual mouse callback function
def print_coords(event,x,y,flags,param):
# Global variables needed
global image,image_copy,r_start,c_start
# If left mouse button is clicked,start of line
if (event == cv2.EVENT_LBUTTONDOWN):
r_start = x
c_start = y
# If left mouse button is clicked,end of line; plot intensity profile
if (event == cv2.EVENT_LBUTTONUP):
r_end = x
c_end = y
image = cv2.line(image_copy.copy(),(r_start,c_start),(r_end,c_end),(255,255,255),2)
line = np.transpose(np.array(draw.line(r_start,c_start,r_end,c_end)))
data = image_copy.copy()[line[:,1],line[:,0],:]
plt.close()
plt.figure('Intensity profile')
plt.plot(data[:,'b',data[:,'g',2],'r')
plt.draw()
plt.pause(0.001)
plt.legend(['Blue','Green','Red'])
plt.ylim((0,255))
# Read an image
image = cv2.imread('path/to/your/image.png',cv2.IMREAD_COLOR)
image_copy = image.copy()
# Set up window and mouse callback function
cv2.namedWindow("image")
cv2.setMouseCallback("image",print_coords)
# Loop until the 'c' key is pressed
while True:
# Display image; wait for keypress
cv2.imshow("image",image)
key = cv2.waitKey(1) & 0xFF
# If 'c' key is pressed,break from loop
if key == ord("c"):
break
cv2.destroyAllWindows()
要获取直线的坐标,请使用scikit-image中的line
函数。这似乎是最快的Python方式。
希望能帮助Python人士寻找这样的功能!
,是的,它叫做LineIterator。
// grabs pixels along the line (pt1,pt2)
// from 8-bit 3-channel image to the buffer
LineIterator it(img,pt1,pt2,8);
LineIterator it2 = it;
vector<Vec3b> buf(it.count);
for(int i = 0; i < it.count; i++,++it)
buf[i] = *(const Vec3b*)*it;
// alternative way of iterating through the line
for(int i = 0; i < it2.count; i++,++it2)
{
Vec3b val = img.at<Vec3b>(it2.pos());
CV_Assert(buf[i] == val);
}
更多信息在这里:
https://docs.opencv.org/master/dc/dd2/classcv_1_1LineIterator.html