opencv 读取图片后通道为BGR的格式,这里做个示范将图片的左半边设置为透明效果。
import cv2
import numpy as np
img = cv2.imread("/home/shuai/Desktop/lena.jpg")
b_channel, g_channel, r_channel = cv2.split(img)
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
# 最小值为0
alpha_channel[:, :int(b_channel.shape[0] / 2)] = 100
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
cv2.imwrite("lena.png", img_BGRA)
原图
透明图 (100)
透明图(0)
根据bbox生成该区域的抠图
img = cv2.imread("/home/shuai/Desktop/tool/lena.jpg")
# [x,y,width,height]
bbox = [200, 200, 200, 200]
## 1 截取bbox区域
img_crop = img[bbox[1]:bbox[1] + bbox[3], bbox[0]:bbox[0] + bbox[2], :]
cv2.imshow('crop_image', img_crop)
## 2 通过加入alpha通道实现矩形区域提取
bbox_index = np.zeros([*img.shape[:2]]).astype(np.bool)
bbox_index[bbox[1]:bbox[1] + bbox[3], bbox[0]:bbox[0] + bbox[2]] = True
b_channel, g_channel, r_channel = cv2.split(img)
alpha_channel = np.zeros(b_channel.shape, dtype=b_channel.dtype)
alpha_channel[np.where(bbox_index)] = 255
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
# cv2.imwrite("test.png", img_BGRA)bbox_index
# cv2.imshow('transparent_image', img_BGRA) # cv2.imshow不会考虑alpha通道,因此show之后还是整张图像,可以保存再查看
## 3 把矩形外的像素设置为特定颜色,例如黑色
img[np.where(~bbox_index)] = 0
cv2.imshow('bk_image', img)
cv2.waitKey()
多个bbox生成区域的抠图
img = cv2.imread("/home/shuai/Desktop/tool/lena.jpg")
# [x,y,width,height]
bboxes = [[200, 200, 200, 200],
[100, 100, 100, 100],
[190, 80, 90, 300]]
bbox_index = np.zeros([*img.shape[:2]]).astype(np.bool)
for bbox in bboxes:
bbox_index[bbox[1]:bbox[1] + bbox[3], bbox[0]:bbox[0] + bbox[2]] = True
## 把矩形外的像素设置为特定颜色,例如黑色
img[np.where(~bbox_index)] = 0
cv2.imshow('bk_image', img)
cv2.waitKey()