python - 使用opencv python从图像裁剪圆圈

标签 python opencv image-processing

我想在下图中裁剪圆圈:

enter image description here

我的代码,我能够检测到圆圈但不能裁剪它:

import cv2
#import cv2.cv as cv
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)

edges = cv2.Canny(thresh, 100, 200)
#cv2.imshow('detected ',gray)
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(img1,(i[0],i[1]),i[2],(0,255,0),2)

#Code to close Window
cv2.imshow('detected Edge',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()

最佳答案

<强>1。创建 mask :

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)

# Create mask
height,width = img.shape
mask = np.zeros((height,width), np.uint8)

edges = cv2.Canny(thresh, 100, 200)
#cv2.imshow('detected ',gray)
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
    # Draw on mask
    cv2.circle(mask,(i[0],i[1]),i[2],(255,255,255),thickness=-1)

# Copy that image using that mask
masked_data = cv2.bitwise_and(img1, img1, mask=mask)

# Apply Threshold
_,thresh = cv2.threshold(mask,1,255,cv2.THRESH_BINARY)

# Find Contour
contours = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
x,y,w,h = cv2.boundingRect(contours[0])

# Crop masked_data
crop = masked_data[y:y+h,x:x+w]

#Code to close Window
cv2.imshow('detected Edge',img1)
cv2.imshow('Cropped Eye',crop)
cv2.waitKey(0)
cv2.destroyAllWindows()

使用您的图片的结果:

enter image description here

关于python - 使用opencv python从图像裁剪圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36911877/

相关文章:

python - ImportError : numpy. core.multiarray 导入失败

opencv - 将 Mat 数组从 jni 返回到 java

opencv - android ndk中如何同时处理8UC​​3和8UC4

用于云中托管图像的 Javascript 灰度脚本

image - OpenCV - 从图像中删除水平点或线导致图像质量较低

java - 如何从图像中剪切并保存矩形?

python - 如何检查矩阵是否稀疏

python - 如何将 os.system() 的输出存储在变量中

Python 3 : capture a matrix return from subprocess with Rscript

python - 使用 conda 和 python3k 构建包