pythonopencv如何盖图像_Python OpenCV-用透明度覆盖图像

我要做的是把一个透明的图像放在另一个上面。像这样的:

njwGd.png

我还没有找到任何解决方案,所以我决定逐像素计算得到的颜色。那个对我有用,但很慢。

我对OpenCV和Python都是新手。

这是我的密码,我想到了:import numpy as np

import cv2

img1 = cv2.imread("img1.png", -1)

img2 = cv2.imread("img2.png", -1) # this one has transparency

h, w, depth = img2.shape

result = np.zeros((h, w, 3), np.uint8)

for i in range(h):

for j in range(w):

color1 = img1[i, j]

color2 = img2[i, j]

alpha = color2[3] / 255.0

new_color = [ (1 - alpha) * color1[0] + alpha * color2[0],

(1 - alpha) * color1[1] + alpha * color2[1],

(1 - alpha) * color1[2] + alpha * color2[2] ]

result[i, j] = new_color

cv2.imshow("result", result)

cv2.waitKey(0)

cv2.destroyAllWindows()

还有别的办法吗?快一点,快一点?

谢谢。

要裁剪一个圆形图像并将其余部分设置为透明,可以使用以下步骤: 1. 读取图像并将其转换为灰度图像。 ``` import cv2 img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ``` 2. 使用霍夫圆变换检测图像中的圆形,并确定其半径和圆心坐标。 ``` circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=0, maxRadius=0) x, y, r = int(circles[0][0][0]), int(circles[0][0][1]), int(circles[0][0][2]) ``` 3. 创建一个具有相同大小的掩码图像并将其所有像素设置为零。然后,使用cv2.circle函数在掩码图像上绘制圆形区域。 ``` mask = np.zeros_like(gray) cv2.circle(mask, (x, y), r, (255, 255, 255), -1) ``` 4. 将原始图像与掩码图像进行按位与运算,以删除圆形以外的所有像素。 ``` result = cv2.bitwise_and(img, img, mask=mask) ``` 5. 将图像保存为png格式文件,以便保留透明度信息。 ``` cv2.imwrite('result.png', result) ``` 完整代码如下: ``` import cv2 import numpy as np img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=0, maxRadius=0) x, y, r = int(circles[0][0][0]), int(circles[0][0][1]), int(circles[0][0][2]) mask = np.zeros_like(gray) cv2.circle(mask, (x, y), r, (255, 255, 255), -1) result = cv2.bitwise_and(img, img, mask=mask) cv2.imwrite('result.png', result) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值