gpt4 book ai didi

python - 删除图像的背景

转载 作者:行者123 更新时间:2023-12-02 16:01:53 34 4
gpt4 key购买 nike

我正在尝试去除图像的背景(背景可以是任何其他颜色或包含噪声、灰尘等)

这是图片:

enter image description here

这是我的代码:

import cv2

img = cv2.imread('image.jpg', 0)

norm_img = np.zeros(img.shape)

normim = cv2.normalize(img, norm_img, 0, 255, cv2.NORM_MINMAX)

_, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5,5),np.uint8)

opening = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)

mask_inv = cv2.bitwise_not(opening)

seg = cv2.add(mask_inv, normim)

输出:

enter image description here

代码将对原始图像进行归一化,然后添加应用形态学的图像,这是一个二值图像。

归一化原始图像并应用形态学原始图像的结果:

enter image description here enter image description here

那么我的代码会发生什么,我怎样才能删除背景?

最佳答案

您可以使用 Numpy 和 Python/OpenCV 执行此操作,如下所示:

输入:

enter image description here

面具:

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread('fingerprint.jpg')

# read mask as grayscale
mask = cv2.imread('mask.jpg', cv2.IMREAD_GRAYSCALE)

# threshold mask
thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# apply mask to image
result = img.copy()
result[thresh==0] = (255,255,255)

# save results
cv2.imwrite('fingerprint_masked.jpg', result)

cv2.imshow('masked image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()


结果:

enter image description here

关于python - 删除图像的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62421455/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com