python +opencv 自动消除红眼

您所在的位置:网站首页 怎么去除照片中的红眼 python +opencv 自动消除红眼

python +opencv 自动消除红眼

2024-07-13 02:16| 来源: 网络整理| 查看: 265

红眼形成?

由于相机曝光,进光量太大造成,红眼毫无疑问红色通道的值要大于绿色和蓝色,那么就要想办法用绿色和蓝色组合

如何消除红眼?

1、眼睛检测--利用opencv 自带的xml,笔者以前的博客很多这种

2、构造mask

mask=r>150&r>(b+g)笔者在加上r>150的时候,有问题,所以只保留了如r>(b+g)这个

3、对于mask 进行填洞,因为得到mask可能存在空缺

4、这一步就是如何替换红眼了,有两种方法:

1)用绿色和蓝色的均值替换红色通道

2)用绿色和蓝色的均值替换所有通道

方法1效果图如下:

可以看见眼珠子是紫色

方法2 效果图如下:

眼珠子正常,所以要用蓝色和绿色的均值替换所有通道

代码如下:

import numpy as np import cv2 class red_eye_elimate(object): def __init__(self,file_path): self.file_path=file_path @staticmethod def fillhole(thresh): h,w=thresh.shape[:] mask=np.zeros((h+2,w+2),np.uint8) holes=cv2.floodFill(thresh.copy(),mask,(0,0),255) s=cv2.bitwise_not(holes[1]) full_thresh=s|thresh return full_thresh def detect_eye_and_elimate(self): eye=cv2.CascadeClassifier('haarcascade_eye.xml') eye.load(r'E:\opencv\opencv\sources\data\haarcascades\haarcascade_eye.xml') image=cv2.imread(self.file_path) eyes=eye.detectMultiScale(image,1.03,20,0,(40,40)) if len(eyes)!=0: for x,y,w,h in eyes: eye_image_bgr=image[y:y+h,x:x+w] r=eye_image_bgr[:,:,2] b=eye_image_bgr[:,:,0] g=eye_image_bgr[:,:,1] mask=r>(cv2.add(b,g)) mask = mask.astype(np.uint8)*255 full_mask=self.fillhole(np.uint8(mask*255)) mean=cv2.add(b,g)/2 mean=mean.astype(np.uint8) eye_copy=eye_image_bgr.copy() np.copyto(eye_copy,mean[:,:,np.newaxis],where=full_mask.astype(np.bool)[:,:,np.newaxis]) image[y:y+h,x:x+w]=eye_copy return image if __name__=="__main__": file_path=r"C:\Users\Y\Desktop\red\1.png" red=red_eye_elimate(file_path) image=red.detect_eye_and_elimate() cv2.imshow("sa",image),cv2.waitKey(0)

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3