接下来会将日常工作中使用到的图像处理工具,以易用函数的形式发布于CSDN博文中
以下这个实用的工具或函数,作用是知道图像中某一感兴趣矩形区域,顺时针的四点坐标,如图:
图1 任意角度矩形区域
获取上图中已知矩形区域的图像,python代码如下:d
def CutImgeByBox(output,box):
"""
根据任意内接矩形,四点(顺时针)box[[x1,y2],[x2,y2],[x3,y3],[x4,y4]],从输入图像中,截取图像
"""
if type(box)==type([]):
pts1 = np.float32(box)
if pts1.shape==(4,2):
# 变换后的矩形四个顶点坐标
dy=int(np.sqrt((box[0][0]-box[1][0])**2+(box[0][1]-box[1][1])**2))
dx=int(np.sqrt((box[1][0]-box[2][0])**2+(box[1][1]-box[2][1])**2))
pts2 = np.float32([[1, dy+1],
[1, 1],
[1+dx, 1],
[1+dx, 1+dy]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(output, M, (output.shape[1],output.shape[0]))
target = dst[int(pts2[1][1]):int(pts2[0][1]),int(pts2[1][0]):int(pts2[2][0]),:]
return True,target
else:
print("box shape is wrong ,must be list as (4,2)")
return False,output
else:
print("box type is wrong,must be list as [[x1,y2],[x2,y2],[x3,y3],[x4,y4]]")
return False,output
注:输入的矩形框四点的格式应为list格式,如:[[x1,y2],[x2,y2],[x3,y3],[x4,y4]]
仅供参考。