img1为带黑边的原始图像,warp_imgs为图像矫正透视变换后的去黑边图像,其余py文件分享在下面,计算周长的代码自行去获取轮廓周长套公式(1)进行计算:
get_area_final.py:
import cv2
import numpy as np
def sort_contours_size(cnts):
"""根据大小对轮廓进行排序"""
cnts_sizes = []
for contour in cnts:
cnt_size = cv2.contourArea(contour)
cnts_sizes.append([cnt_size,contour])
cnts_sizes.sort(key=lambda x:x[0], reverse=True)
return cnts_sizes
def get_area_main(path):
img = cv2.imread(path)
#变成单通道的黑白图片
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#二值化 返回阈值和二值化后图
thresh,binary = cv2.threshold(gray,150,255,cv2.THRESH_BINARY)
# cv2.imshow("img1",binary)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# 查找轮廓 返回轮廓和层级
contours, hierarchy = cv2.findContours(binary.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓会直接修改原图
img_copy = img.copy()
cv2.drawContours(img_copy, contours, -1, (0, 0, 255), 2)
# cv2.imshow('img_con', img_copy)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
contour_sizes = sort_contours_size(contours)
cnt = contour_sizes[1][1]
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
# print(center,radius)
cv2.circle(img_copy, center, radius, (255, 0, 0), 2)