如何在skimage中准确估计仿射变换矩阵实现图像三角区域变换
问题根因定位
1. 坐标顺序和接口要求不匹配
- scikit-image 所有像素坐标相关接口(包括
draw.polygon2mask、AffineTransform.estimate),默认接收的坐标格式为 (行号, 列号),和图像数组的shape维度(高、宽、通道)完全对应。 - 你定义的
uv_coords_src、uv_coords_dst是按图形学uv坐标的习惯存储:第一个值是横向位置u(对应图像的列号),第二个值是纵向位置v(对应图像的行号)。直接把这套顺序的坐标传入接口时,系统会把你标注的横向u值当成纵向行号、纵向v值当成横向列号,不仅导致绘制的mask三角块和你在图上标记的红色/绿色位置完全错位,还会让部分坐标值超出图像边界,最终基于错误顶点估计的仿射变换自然不符合预期。
2. 图像尺寸的认知偏差
- 代码调用的
data.chelsea()图像实际尺寸为(451, 300, 3),也就是纵向行方向总长度451像素,横向列方向总长度300像素,和多数人默认的「高300、宽450」的印象有差异,这也是部分坐标值未换位时看起来超出合理范围的原因。
修正方案
- 对所有顶点坐标做顺序互换,从原格式
[u(列), v(行)]调整为接口要求的[v(行), u(列)]格式,确保多边形绘制、变换矩阵估计的顶点和你标注的实际位置完全对齐。 - 其余逻辑保持不变即可,scikit-image 的
warp函数会自动对传入的正向仿射变换做逆变换处理,不需要手动调整变换方向。
修正后完整代码
import numpy as np from skimage import draw from skimage import transform from skimage import img_as_float from skimage import data from matplotlib import pyplot as plt # 原uv坐标:[u(横向列), v(纵向行)],自动调整为接口需要的[v(纵向行), u(横向列)]格式 uv_coords_src = np.array([[239,287], [101,340], [96,196]])[:, ::-1] uv_coords_dst = np.array([[253,179], [170,70], [263,46]])[:, ::-1] img = img_as_float(data.chelsea()) # 绘制源三角mask、目标三角参考mask mask = draw.polygon2mask(image_shape=img.shape, polygon=uv_coords_src) mask_out = draw.polygon2mask(image_shape=img.shape, polygon=uv_coords_dst) masked_image = img * mask masked_image_out = img * (mask + mask_out) # 估计仿射变换矩阵 tform3 = transform.AffineTransform() tform3.estimate(uv_coords_src, uv_coords_dst) warped = transform.warp(masked_image, tform3, output_shape=img.shape) # 绘图展示 fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) ax1.imshow(img, cmap='gray') ax1.set_title("原图") ax2.imshow(masked_image_out, cmap='gray') ax2.set_title("源/目标三角标记图") ax3.imshow(warped, cmap='gray') ax3.set_title("修正后变换结果") plt.show()
补充说明:代码里用
[:, ::-1]对每个坐标点的两个值做了逆序操作,不需要手动逐个修改坐标值,后续如果要调整顶点位置,直接按原uv格式输入即可。
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

