900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > OpenCV剪切图片圆形区域

OpenCV剪切图片圆形区域

时间:2023-11-07 10:34:40

相关推荐

OpenCV剪切图片圆形区域

《OpenCV系列教程》

项目位置:OpenCV-Sample

代码位置:30-CutCircularArea.py

效果如下:

代码:

import cv2import numpy as np#加载图片img = cv2.imread('./res/icon.png', cv2.IMREAD_UNCHANGED)#获取图片尺寸height, width = img.shape[:2]height = int(height)width = int(width)#生成内显示模板circleIn = np.zeros((height, width, 1), np.uint8)circleIn = cv2.circle(circleIn, (width // 2, height // 2), min(height, width) // 2, (1), -1)#实际使用中不需要写入文件#np.savetxt('./out/circle.txt', circleIn[:, :, 0], fmt="%d", delimiter="")#生成外显示模板circleOut = circleIn.copy()circleOut[circleOut == 0] = 2circleOut[circleOut == 1] = 0circleOut[circleOut == 2] = 1#实际使用中不需要写入文件#np.savetxt('./out/circle1.txt', circleOut[:, :, 0], fmt="%d", delimiter="")#原图与内显示模板融合#生成空白图片imgIn = np.zeros((height, width, 4), np.uint8)#复制前3个通道imgIn[:, :, 0] = np.multiply(img[:, :, 0], circleIn[:, :, 0])imgIn[:, :, 1] = np.multiply(img[:, :, 1], circleIn[:, :, 0])imgIn[:, :, 2] = np.multiply(img[:, :, 2], circleIn[:, :, 0])#设置α通道的不透明部分circleIn[circleIn == 1] = 255imgIn[:, :, 3] = circleIn[:, :, 0]cv2.imwrite('./out/imgIn.png', imgIn)#外显示与内显示同理imgOut = np.zeros((height, width, 4), np.uint8)imgOut[:, :, 0] = np.multiply(img[:, :, 0], circleOut[:, :, 0])imgOut[:, :, 1] = np.multiply(img[:, :, 1], circleOut[:, :, 0])imgOut[:, :, 2] = np.multiply(img[:, :, 2], circleOut[:, :, 0])circleOut[circleOut == 1] = 255imgOut[:, :, 3] = circleOut[:, :, 0]cv2.imwrite('./out/imgOut.png', imgOut)

文中产生的两个模板。如果打印出来就是下面的效果。打开np.savetxt这行的注释。

显示1的部分,效果就是中间显示周边不显示。

一样显示1的部分,周边显示,中间不显示。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。