如何调整图像绘制线条宽度以获取多像素坐标并计算平均强度?
解决方案:实现带厚度的线条像素强度均值计算
我明白你的困扰——现在你只是改了绘图时线条的视觉粗细,但实际只取了路径上单个像素的强度。要真正实现按指定厚度取宽度范围内的像素均值,咱们需要从路径几何计算和像素范围选取这两方面入手,下面是具体的实现思路和修改后的代码:
核心思路
- 路径密集化:你当前的点击点是离散的折线,先把这些点插值成更密集的连续路径,避免强度曲线出现跳变;
- 垂直方向计算:对路径上的每个点,计算路径在该点的切线方向,进而得到垂直于路径的方向(也就是线条厚度的延伸方向);
- 像素范围选取:根据设定的厚度,在垂直方向上选取左右/上下的所有像素,收集它们的强度值并计算均值;
- 替换原强度获取逻辑:把原来只取单个像素的代码,替换成上述带厚度的均值计算逻辑。
修改后的完整代码
首先需要导入scipy.interpolate来做路径插值,如果你还没装scipy,可以用pip install scipy安装。
import numpy as np import matplotlib.pyplot as plt from PIL import Image import sys from scipy.interpolate import interp1d """This class is a modification of the code created by Joerg Doepfert 2014 based on code posted by Daniel Kornhauser.""" class roipoly: def __init__(self, fig=[], ax=[], roicolor='b',thickness=2): if fig == []: fig = plt.gcf() if ax == []: ax = plt.gca() self.previous_point = [] self.allxpoints = [] self.allypoints = [] self.start_point = [] self.end_point = [] self.line = None self.roicolor = roicolor self.thickness = thickness # 视觉线条厚度 self.fig = fig self.ax = ax self.__ID1 = self.fig.canvas.mpl_connect('motion_notify_event', self.__motion_notify_callback) self.__ID2 = self.fig.canvas.mpl_connect('button_press_event', self.__button_press_callback) if sys.flags.interactive: plt.show(block=False) else: plt.show() def displayIAL(self, **linekwargs): l = plt.Line2D(self.allxpoints,self.allypoints,color=self.roicolor,linewidth=self.thickness,**linekwargs) values=(self.allxpoints,self.allypoints) ax = plt.gca() ax.add_line(l) plt.draw() return values def __motion_notify_callback(self, event): if event.inaxes: ax = event.inaxes x, y = event.xdata, event.ydata if (event.button == None or event.button == 1) and self.line != None: # Move line around self.line.set_data([self.previous_point[0], x],[self.previous_point[1], y]) self.fig.canvas.draw() def __button_press_callback(self, event): if event.inaxes: x, y = event.xdata, event.ydata ax = event.inaxes if event.button == 1 and event.dblclick == False: # 左键单击添加线段点 if self.line == None: self.line = plt.Line2D([x, x],[y, y],marker='o',color=self.roicolor, linewidth=self.thickness) self.start_point = [x,y] self.previous_point = self.start_point self.allxpoints=[x] self.allypoints=[y] ax.add_line(self.line) self.fig.canvas.draw() else: self.line = plt.Line2D([self.previous_point[0], x],[self.previous_point[1], y],marker = 'o',color=self.roicolor,linewidth=self.thickness) self.previous_point = [x,y] self.allxpoints.append(x) self.allypoints.append(y) event.inaxes.add_line(self.line) self.fig.canvas.draw() elif ((event.button == 1 and event.dblclick==True) or (event.button == 3 and event.dblclick==False)) and self.line != None: # 双击左键/右键单击闭合路径 self.fig.canvas.mpl_disconnect(self.__ID1) self.fig.canvas.mpl_disconnect(self.__ID2) self.line.set_data([self.previous_point[0],self.start_point[0]],[self.previous_point[1],self.start_point[1]]) ax.add_line(self.line) self.fig.canvas.draw() self.line = None if sys.flags.interactive: pass else: plt.close(self.fig) # 获取用户绘制的路径坐标 def getIAL(img, width): im = np.array(img) plt.imshow(im, interpolation='nearest', cmap="Greys") plt.title("左键单击:添加线段点,右键单击:闭合路径") ROIl = roipoly(roicolor='g',thickness=width) plt.imshow(im, interpolation='nearest', cmap="Greys") myIAL=ROIl.displayIAL() plt.clf() return myIAL # 新增:计算带厚度的线条强度均值 def get_thick_line_intensities(x_coords, y_coords, image_array, thickness): # 1. 先将离散路径插值为密集路径 # 计算每个点到起点的累积距离 distances = np.cumsum(np.sqrt(np.diff(x_coords)**2 + np.diff(y_coords)**2)) distances = np.insert(distances, 0, 0) # 起点距离为0 # 生成更密集的距离采样点(比如每0.5像素一个点) dense_distances = np.linspace(0, distances[-1], int(distances[-1]*2)) # 插值x和y坐标 interp_x = interp1d(distances, x_coords, kind='linear')(dense_distances) interp_y = interp1d(distances, y_coords, kind='linear')(dense_distances) intensity_values = [] half_thickness = thickness / 2.0 for i in range(len(interp_x)): x = interp_x[i] y = interp_y[i] # 2. 计算当前点的路径切线方向 if i == 0: # 第一个点,用下一个点的方向 dx = interp_x[i+1] - interp_x[i] dy = interp_y[i+1] - interp_y[i] elif i == len(interp_x)-1: # 最后一个点,用上一个点的方向 dx = interp_x[i] - interp_x[i-1] dy = interp_y[i] - interp_y[i-1] else: # 中间点,用前后点的平均方向 dx = (interp_x[i+1] - interp_x[i-1])/2 dy = (interp_y[i+1] - interp_y[i-1])/2 # 计算垂直于切线的单位向量(两个方向,取其中一个即可) length = np.sqrt(dx**2 + dy**2) if length == 0: # 避免除以0,直接取上下方向 perp_dx, perp_dy = 0, 1 else: perp_dx = -dy / length perp_dy = dx / length # 3. 生成垂直方向上的所有像素坐标 # 计算偏移范围:从-half_thickness到half_thickness,步长为1像素 offsets = np.arange(-half_thickness, half_thickness + 1, 1) pixels_x = x + offsets * perp_dx pixels_y = y + offsets * perp_dy # 转换为整数像素坐标,并过滤超出图像范围的点 pixels_x = np.round(pixels_x).astype(int) pixels_y = np.round(pixels_y).astype(int) valid_mask = (pixels_x >= 0) & (pixels_x < image_array.shape[1]) & (pixels_y >=0) & (pixels_y < image_array.shape[0]) valid_x = pixels_x[valid_mask] valid_y = pixels_y[valid_mask] # 4. 计算这些像素的强度均值 if len(valid_x) == 0: intensity = 0.0 else: intensity = np.mean(image_array[valid_y, valid_x]) intensity_values.append(intensity) return dense_distances, intensity_values # 绘制强度曲线 def IAL_Plot(IAL, image, thickness=5): xvalues = IAL[0] yvalues = IAL[1] imarray = np.array(image) distances, intensity_values = get_thick_line_intensities(xvalues, yvalues, imarray, thickness) plt.plot(distances, intensity_values) plt.xlabel('沿线条的距离(像素)', fontsize=16) plt.ylabel('平均强度',fontsize=16) plt.show() # 测试代码 if __name__ == "__main__": # 生成渐变灰度图 array = np.linspace(0,1,256*256) mat = np.reshape(array,(256,256)) img = Image.fromarray(np.uint8(mat*255),'L') line_visual_thickness = 5 myIAL = getIAL(img, line_visual_thickness) IAL_Plot(myIAL, img, thickness=line_visual_thickness)
关键修改点说明
- 路径插值:用
scipy.interpolate.interp1d把离散的点击点转换成连续的密集路径,这样强度曲线更平滑,不会因为点间距大而出现断层; - 垂直方向计算:对每个点计算路径的切线方向,再得到垂直方向,确保我们是沿着线条的厚度方向选取像素,而不是固定的x/y方向;
- 像素范围过滤:选取垂直方向的像素后,过滤掉超出图像边界的点,避免索引错误;
- 均值计算:对每个点的有效像素取均值,替换原来只取单个像素的逻辑。
额外建议
- 如果需要处理平滑曲线,可以把插值的
kind参数改成'cubic',得到更贴合的路径; - 如果图像很大导致性能不足,可以减少插值的密度,或者对线段批量处理,而不是逐个点计算;
- 你可以把视觉厚度和实际采样厚度绑定成同一个参数,让操作更直观。
内容的提问来源于stack exchange,提问作者R. Patterson
相关产品推荐
相关产品推荐

