使用opencv python从图像裁剪圆

编程入门 行业动态 更新时间:2024-10-27 16:29:16
本文介绍了使用opencv python从图像裁剪圆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要在下图中裁剪圆圈:

I want to crop circle in following image:

我的代码,我能够检测到圆形,但无法裁剪圆形:

My code, I'm able to detect the circle but not to crop it :

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.创建遮罩:

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

2.在该蒙版上绘制圆圈(将厚度设置为-1以填充圆圈):

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.裁剪masked_data

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()

使用图片的结果:

更多推荐

使用opencv python从图像裁剪圆

本文发布于:2023-05-26 09:50:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/252278.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   opencv   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!