图像轮廓最大内接矩形的求法
平时工作中图像处理经常会用到图像最大轮廓及最小外接矩形的获取:
计算过程如下:
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)
然而有时候我们需要的是最大内接矩形:
从轮廓中所有坐标中获取其中4个坐标即可:
获取过程如下:
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) xs = [i[0] for i in rect] ys = [i[1] for i in rect] xs.sort() ys.sort() #内接矩形的坐标为 print(xs[1],xs[2],ys[1],ys[2])