如何遮罩圆形区域? [英] How to mask circular area?

查看:129
本文介绍了如何遮罩圆形区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在图像中遮盖圆形区域.我将代码和输出图像放在下面.如您所见,我在虹膜周围绘制了一个圆形.在这一点之后,我想涂黑圆形区域之外的所有内容.我需要继续吗?还有其他方法吗?

I am trying to mask circular area in image.I put the code and the output image below.As you can see,I draw the circle around iris.After this point,I want to black out everything outside circular area.How do I need to continue?Are there another ways to do so?

谢谢...

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('i1.jpg',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,
                    param1=50,param2=50,minRadius=30,maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
     # draw the outer circle
     cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
     # draw the center of the circle
     cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
cv2.imwrite("iris.jpg",cimg)
plt.imshow(cimg, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()

在此处输入图像描述

推荐答案

首先,HoughCircles函数返回一系列恰好在图像上的圆圈.在您的情况下,您的图像只有一个圆,因此您的代码仅在虹膜周围显示一个圆圈.首先,您必须确定哪个圆与虹膜相对应.

First of all, HoughCircles function returns a series of circles that happens to be on image. In your case, your image has only one cirle, therefore your code shows only one circle around the iris. You have to decide which circle corresponds to the iris in the first place.

假设图像上只有一个圆圈,即虹膜".您可以遍历图像中的所有像素,并检查它们是否靠近圆心.如果没有,则可以将像素值更改为0,这对应于黑色.

Let's assume there is only one circle, which is iris, on your image. You can traverse all the pixels in your image and check if they are close to the center of circle. If it doesn't, you can change pixel value by 0, which corresponds to black.

import cv2
import numpy as np
from matplotlib import pyplot as plt
from math import hypot

img = cv2.imread('asd.png',0)
img = cv2.medianBlur(img,5)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,param1=50,param2=50,minRadius=30,maxRadius=0)
circles = np.uint16(np.around(circles))

x, y, r = circles[0,:][0]
rows, cols = img.shape

for i in range(cols):
    for j in range(rows):
        if hypot(i-x, j-y) > r:
            img[j,i] = 0

cv2.imwrite("iris.jpg",img)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()

这篇关于如何遮罩圆形区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆