OpenCV剪切图片圆形区域

本篇博客主要介绍如何利用OpenCV进行圆形区域的图片裁剪,通过提供的代码示例,展示了两种不同的显示效果,一种是中间显示,周边不显示,另一种是周边显示,中间不显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《OpenCV系列教程》
项目位置:OpenCV-Sample
代码位置:30-CutCircularArea.py
效果如下:
在这里插入图片描述
代码:

import cv2
import 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] = 2
circleOut[circleOut == 1] = 0
circleOut[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] = 255
imgIn[:, :, 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] = 255
imgOut[:, :, 3] = circleOut[:, :, 0]
cv2.imwrite('./out/imgOut.png', imgOut)

文中产生的两个模板。如果打印出来就是下面的效果。打开np.savetxt这行的注释。
显示1的部分,效果就是中间显示周边不显示。
在这里插入图片描述

一样显示1的部分,周边显示,中间不显示。
在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值