1. 制作口罩:
height,width = img.shape
mask = np.zeros((height,width), np.uint8)
2. 在该掩模上绘制圆圈(将线条粗细设置为-1以填充圆圈):
circle_img = cv2.circle(mask,(i[0],i[1]),i[2],(255,255,255),thickness=-1)
3. 使用该遮罩复制该图像:
masked_data = cv2.bitwise_and(img1, img1, mask=circle_img)
4. 应用阈值
_,thresh = cv2.threshold(mask,1,255,cv2.THRESH_BINARY)
5. 寻找轮廓
contours = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
x,y,w,h = cv2.boundingRect(contours[0])
6. 裁剪掩蔽数据
crop = masked_data[y:y+h,x:x+w]
将此代码添加到您的代码中
import cv2
import numpy as np
img1 = cv2.imread('amol.jpg')
img = cv2.imread('amol.jpg',0)
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)
height,width = img.shape
mask = np.zeros((height,width), np.uint8)
edges = cv2.Canny(thresh, 100, 200)
cimg=cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, 1, 10000, param1 = 50, param2 = 30, minRadius = 0, maxRadius = 0)
for i in circles[0,:]:
i[2]=i[2]+4
cv2.circle(mask,(i[0],i[1]),i[2],(255,255,255),thickness=-1)
masked_data = cv2.bitwise_and(img1, img1, mask=mask)
_,thresh = cv2.threshold(mask,1,255,cv2.THRESH_BINARY)
contours = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
x,y,w,h = cv2.boundingRect(contours[0])
crop = masked_data[y:y+h,x:x+w]
cv2.imshow('detected Edge',img1)
cv2.imshow('Cropped Eye',crop)
cv2.waitKey(0)
cv2.destroyAllWindows()
使用您的图像得出的结果: