人物照片怎么去除背景抠出人物python代码
时间: 2023-07-23 12:35:38 浏览: 209
人物照片去除背景的方法有很多,以下是一个基于OpenCV的示例代码:
```python
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用自适应阈值法对图像进行二值化处理
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2)
# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 创建掩膜
mask = np.zeros(img.shape[:2], dtype=np.uint8)
# 绘制轮廓
for cnt in contours:
cv2.drawContours(mask, [cnt], 0, 255, -1)
# 对图像进行掩膜处理
res = cv2.bitwise_and(img, img, mask=mask)
# 显示图像
cv2.imshow('image', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上代码首先读取一张图像,然后将其转换为灰度图像,并使用自适应阈值法对图像进行二值化处理。接着使用`cv2.findContours`函数查找轮廓,然后创建一个掩膜并在其中绘制所有的轮廓。最后使用`cv2.bitwise_and`函数对原图像和掩膜进行按位与操作,得到去除背景的图像。你可以根据自己的需求对以上代码进行修改。
阅读全文
相关推荐
















