不同的背景相同的图像,但不同的大小

时间:2013-02-11 06:46:50

标签: python image-processing

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

编辑:我无法评论任何答案,不明白为什么。请回复。

1 个答案:

答案 0 :(得分:2)

如果您可以在结果图像中容忍一些难看的效果,这很容易做到。如果具有不同背景颜色的图像将显示为原始图像的缩小版本,则这些效果可能不明显且一切都很好。

所以这是一个简单的方法:

  • 从(0,0)处的像素填充填充,假设它是背景像素(示例中为白色),并在执行填充填充时接受微小差异。背景像素由透明点替换。
  • 上面的步骤给出了一个掩码,例如,您可以执行侵蚀和高斯滤波。
  • 使用上面创建的蒙版粘贴“泛光”图像。

以下是您对此方法的期望。输入图像,然后两次转换为不同的背景颜色。

enter image description here enter image description here enter 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])