OpenCV逆极坐标变换warpPolar结果出框及生成完整环形方案咨询
问题根源
你当前代码的异常是三个参数设置错误导致的:
- 最大半径
maxRadius仅设置了环形内半径,没有包含原线条的宽度,导致环形外侧截断 - 逆极坐标变换的中心坐标设置错误,导致生成的环形偏移出输出画布范围
- 补充黑色区域的逻辑不符合极坐标变换的映射规则,原线条对应的是极坐标的角度轴,不需要额外补黑边到半径长度
修正后可生成完整环形的代码
import cv2 import numpy as np # 生成输入直线 line = np.ones(shape=(20,475), dtype=np.uint8)*255 # 顺时针旋转90度,高度对应角度轴总长度,宽度对应环形的线宽 flipped = cv2.rotate(line, cv2.ROTATE_90_CLOCKWISE) h, w = flipped.shape # 计算内半径:角度轴总长度对应2π弧度,所以内半径 = 角度轴长度 / 2π inner_radius = int(h / (2 * np.pi)) # 外半径 = 内半径 + 线宽(也就是旋转后图像的宽度) outer_radius = inner_radius + w # 输出画布尺寸刚好容纳整个环形,留2px边距避免边缘截断 output_size = (outer_radius * 2 + 4, outer_radius * 2 + 4) # 变换中心放在输出画布的中心 center = (output_size[0]//2, output_size[1]//2) # 执行逆极坐标变换 output = cv2.warpPolar( flipped, dsize=output_size, center=center, maxRadius=outer_radius, flags=cv2.WARP_INVERSE_MAP + cv2.WARP_POLAR_LINEAR ) # 效果示意 cv2.imshow('完整环形', output) cv2.waitKey(0)

获取环形bounding box的两种方法
- 直接计算(效率最高):
已知环形的中心坐标(cx, cy)、外半径outer_radius,bounding box的坐标为:
x1 = cx - outer_radius y1 = cy - outer_radius x2 = cx + outer_radius y2 = cy + outer_radius
对应OpenCV的(x,y,w,h)格式为(x1, y1, outer_radius*2, outer_radius*2)
- 轮廓检测(适合不确定环形参数的场景):
# 二值化后找最大轮廓 _, binary = cv2.threshold(output, 127, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) max_contour = max(contours, key=cv2.contourArea) x, y, w, h = cv2.boundingRect(max_contour)
内容的提问来源于stack exchange,提问作者Olca Orakcı
相关产品推荐
相关产品推荐

