gpt4 book ai didi

python - 去除图像背景并提取图像中的对象

转载 作者:行者123 更新时间:2023-12-04 10:38:44 40 4
gpt4 key购买 nike

我知道这里有很多关于这个问题的线索,但我无法用这些答案解决我的问题。我多次尝试使用不同的代码来删除图像的背景,如下所示:
With Background

对此:

Without Background

使用以下代码:

img2 = Image.open("foo.jpg")
c_red, c_green, c_blue = cv2.split(img2)
img2 = cv2.merge((c_red, c_green, c_blue, mask.astype('float32') / 255.0))
img.paste(img2,(0,0))

或使用此代码:
img2 = Image.open("foo.jpg")
img2 = img2.convert("RGBA")
datas = img2.getdata()

newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img2.putdata(newData)

或者:
threshold=100
dist=5
img2 = Image.open("foo.jpg")
img2 = img2.convert("RGBA")

arr=np.array(np.asarray(img2))
r,g,b,a=np.rollaxis(arr,axis=-1)
mask=((r>threshold)
& (g>threshold)
& (b>threshold)
& (np.abs(r-g)<dist)
& (np.abs(r-b)<dist)
& (np.abs(g-b)<dist)
)
arr[mask,3]=0
img2=Image.fromarray(arr,mode='RGBA')

但它们都不起作用。我想要做的是删除任何颜色(透明)的背景并将图像的边框更改为其对象的边框,如上所示。任何帮助表示赞赏。

最佳答案

这是使用 OpenCV 执行此操作的一种方法。这个想法是获得一个二值图像然后使用 cv2.boundingRect获取边界矩形坐标。我们可以使用 Numpy 切片裁剪图像,然后添加一个 alpha channel 。结果如下:

输入图像

enter image description here

要提取的二进制图像和区域

enter image description here

提取的投资返回率

enter image description here

代码

import cv2
import numpy as np

# Load image, convert to grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Obtain bounding rectangle and extract ROI
x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = original[y:y+h, x:x+w]

# Add alpha channel
b,g,r = cv2.split(ROI)
alpha = np.ones(b.shape, dtype=b.dtype) * 50
ROI = cv2.merge([b,g,r,alpha])

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.imshow('ROI', ROI)
cv2.waitKey()

关于python - 去除图像背景并提取图像中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60033008/

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