1.图像轮廓和最小外接矩形
img = cv2.imread(path)
# 图像处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.blur(gray, (9, 9))
_, thresh = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY)
# 获取轮廓
_, cnts, _ = cv2.findContours( thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
#对轮廓按照面积进行排序,选取最大面积
c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
rect = cv2.minAreaRect(c)
#box即为最大面积图像轮廓的的最小外接矩形四点坐标
box = np.int0(cv2.boxPoints(rect))
cv2.drawContours(img, [box], -1, (0, 255, 0), 3)
cv2.imshow("Image", img)
cv2.imwrite("pic.jpg", img)
cv2.waitKey(0)
2.最大内接矩形
def order_points(pts):
# pts为轮廓坐标
# 列表中存储元素分别为左上角,右上角,右下角和左下角
rect = np.zeros((4, 2), dtype = "float32")
# 左上角的点具有最小的和,而右下角的点具有最大的和
s = pts.sum(axis = 1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
# 计算点之间的差值
# 右上角的点具有最小的差值,
# 左下角的点具有最大的差值
diff = np.diff(pts, axis = 1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
# 返回排序坐标(依次为左上右上右下左下)
return rect
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.blur(gray, (9, 9))
_, thresh = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY)
_, cnts, _ = cv2.findContours( thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# 最大面积轮廓
c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
# 先找出轮廓点(顺时针四点坐标)
rect = order_points(c.reshape(c.shape[0], 2))
print(rect)
# 标准化坐标到整数 按照lt rt lb rb 排列
box = np.int0(box)
box_ = sorted(box, key=(lambda x: x[1]))
box_[:2] = sorted(box_[:2], key=(lambda x: x[0]))
box_[2:] = sorted(box_[2:], key=(lambda x: x[0]))
print(box_)
3.透视变换
# 计算透视变换参数矩阵
def cal_perspective_params(aim_point, points):
# 设置偏移点。如果设置为(0,0),表示透视结果只显示变换的部分(也就是画框的部分)
offset_x = 0
offset_y = 0
img_size = (aim_point[1], aim_point[0])
src = np.float32(points)
# 透视变换的四个点
dst = np.float32([[offset_x, offset_y], [img_size[0] - offset_x, offset_y],
[offset_x, img_size[1] - offset_y], [img_size[0] - offset_x, img_size[1] - offset_y]])
# 透视矩阵
M = cv2.getPerspectiveTransform(src, dst)
# print(M)
# # 透视逆矩阵
# M_inverse = cv2.getPerspectiveTransform(dst, src)
# print(M_inverse)
return M
# 透视变换
def img_perspect_transform(img, M, img_size):
img_size = (img_size[1], img_size[0])
return cv2.warpPerspective(img, M, img_size)
# 使用:
'''
:param size: 目标图像的大小 (h, w)
:param box_: 矩形坐标 (左上,右上,左下,右下)
:param origin_img: 被透视变换的图像,一般为原图
'''
M = cal_perspective_params(size, box_)
trasform_img = img_perspect_transform(origin_img, M, size)