def cropCircle(img, resize=None):
if resize:
if (img.shape[0] > img.shape[1]):
tile_size = (int(img.shape[1] * resize / img.shape[0]), resize)
else:
tile_size = (resize, int(img.shape[0] * resize / img.shape[1]))
img = cv2.resize(img, dsize=tile_size, interpolation=cv2.INTER_CUBIC)
else:
tile_size = img.shape
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY);
_, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
main_contour = sorted(contours, key=cv2.contourArea, reverse=True)[0]
ff = np.zeros((gray.shape[0], gray.shape[1]), 'uint8')
cv2.drawContours(ff, main_contour, -1, 1, 15)
ff_mask = np.zeros((gray.shape[0] + 2, gray.shape[1] + 2), 'uint8')
cv2.floodFill(ff, ff_mask, (int(gray.shape[1] / 2), int(gray.shape[0] / 2)), 1)
rect = maxRect(ff)
rectangle = [min(rect[0], rect[2]), max(rect[0], rect[2]), min(rect[1], rect[3]), max(rect[1], rect[3])]
img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]]
cv2.rectangle(ff, (min(rect[1], rect[3]), min(rect[0], rect[2])), (max(rect[1], rect[3]), max(rect[0], rect[2])), 3,
2)
return [img_crop, rectangle, tile_size]
crop.py 文件源码
python
阅读 47
收藏 0
点赞 0
评论 0
评论列表
文章目录