同一背景不同尺寸

2024-05-29 05:25:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些产品图片。这些图像的背景是白色的。现在,在我的网站上,我想在不同的地方使用不同尺寸的相同图像。问题是,因为图像背景的颜色是白色的。但是,我需要的背景颜色是绿色的。同样,作为主产品图像,我希望背景为浅蓝色。这是一个图像的例子。 link。你可以看到这个图像的背景是白色的。我想用和缩略图相同的图像。我写了一个代码来生成图像的缩略图。但我想要背景色。这可以用python中的图像处理来完成吗? 谢谢您。在

编辑:我不能评论任何答案,不能理解为什么。请回答。在


Tags: 代码图像网站颜色尺寸地方link例子
1条回答
网友
1楼 · 发布于 2024-05-29 05:25:23

如果您可以容忍结果图像中的某些丑陋效果,那么这很简单。如果这个背景颜色不同的图像将显示为原始图像的缩小版本,那么这些效果可能不明显,而且一切都是好的。在

下面是一个简单的方法:

  • 从(0,0)处的像素进行整体填充,假设它是背景像素(在示例中为白色),并在执行整体填充时接受较小的差异。背景像素被透明点代替。在
  • 上面的步骤给出了一个掩模,你可以,例如,执行腐蚀和高斯滤波。在
  • 使用上面创建的蒙版粘贴“洪水填充”图像。在

以下是您可以从这种方法中得到的结果。输入图像,然后对不同的背景色进行两次变换。在

enter image description hereenter image description hereenter image description here

import sys
import cv2
import numpy
from PIL import Image

def floodfill(im, grayimg, seed, color, tolerance=15):
    width, height = grayimg.size
    grayim = grayimg.load()
    start_color = grayim[seed]

    mask_img = Image.new('L', grayimg.size, 255)
    mask = mask_img.load()
    count = 0
    work = [seed]
    while work:
        x, y = work.pop()
        im[x, y] = color
        for dx, dy in ((-1,0), (1,0), (0,-1), (0,1)):
            nx, ny = x + dx, y + dy
            if nx < 0 or ny < 0 or nx > width - 1 or ny > height - 1:
                continue
            if mask[nx, ny] and abs(grayim[nx, ny] - start_color) <= tolerance:
                mask[nx, ny] = 0
                work.append((nx, ny))
    return mask_img

img = Image.open(sys.argv[1]).convert('RGBA')
width, height = img.size
img_p = Image.new('RGBA', (width + 20, height + 20), img.getpixel((0, 0)))
img_p.paste(img, (3, 3))
img = img_p
img_g = img.convert('L')
width, height = img.size

im = img.load()
mask = floodfill(im, img_g, (0, 0), (0, 0, 0, 0), 20)

mask = numpy.array(mask)
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
mask = cv2.erode(mask, se)
mask = cv2.GaussianBlur(mask, (9, 9), 3)
mask = Image.fromarray(mask)

result_bgcolor = (0, 0, 0, 255) # Change to match the color you wish.
result = Image.new('RGBA', (width, height), result_bgcolor)
result.paste(img_p, (0, 0), mask)

result.save(sys.argv[2])

相关问题 更多 >

    热门问题