目标描述
使用图像处理方法,将提取到的兴趣区域(倾斜的近似矩形)变换为指定长宽的矩形,供后续操作
区域表示
l : 左 r : 右
t : 上 b : 下
x : x坐标 y : y坐标
quad = [ [l_t_x , l_t_y] , [l_b_x , l_b_y] , [r_b_x , r_b_y] , [r_t_x , r_t_y] ]
quad = [[58.29829508478974, 360.0529870536572],
[56.356932756752556, 391.54706636847766],
[310.46709663801164, 432.40526191708176],
[312.75547128881357, 402.78241825055306]]
区域旋转
#倾斜角度的计算
#quad [[],[],[],[]]
x_dis = quad[2][0] - quad[1][0]
y_dis = quad[2][1] - quad[1][1]
angle = math.degrees(math.atan(y_dis / x_dis))
# 设置喷码区域中心点为固定点
x_center = int((quad[0][0] + quad[1][0] + quad[2][0] + quad[3][0]) / 4)
y_center = int((quad[0][1] + quad[1][1] + quad[2][1] + quad[3][1]) / 4)
# 喷码区域长宽的计算
wide_1 = np.sqrt(np.sum((quad[0] - quad[3]) ** 2))
wide_2 = np.sqrt(np.sum((quad[1] - quad[2]) ** 2))
roi_wide = int(max(wide_1, wide_2))
height_1 = np.sqrt(np.sum((quad[0] - quad[1]) ** 2))
height_2 = np.sqrt(np.sum((quad[3] - quad[2]) ** 2))
roi_height = int(max(height_1, height_2))
# 提取旋转矩阵 sin cos
M = cv2.getRotationMatrix2D((x_center, y_center), angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
# 计算图像的新边界尺寸
(h, w) = img_origin.shape
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
# 旋转
img_affine = cv2.warpAffine(img_origin, M, (nW, nH), flags = cv2.INTER_CUBIC,
borderMode = cv2.BORDER_REPLICATE)
rect = img_affine[max((y_center - roi_height // 2 - 2), 0):(y_center + roi_height // 2 + 2),
max((x_center - roi_wide // 2 - 2), 0):(x_center + roi_wide // 2 + 2)]
区域映射
left_upper = [math.floor(quad[0][0]), math.floor(quad[0][1]) - 2]
left_lower = [math.floor(quad[1][0]), math.ceil(quad[1][1])]
right_lower = [math.ceil(quad[2][0]), math.ceil(quad[2][1])]
pts1 = np.float32([left_upper, left_lower, right_lower])
pts2 = np.float32([[0, 0], [0, img_h], [img_w, img_h]])
M = cv2.getAffineTransform(pts1, pts2)
rect = cv2.warpAffine(binary, M, (img_w, img_h))