相同图像的不同背景,但大小不同
问题描述:
我有一些产品图像。这些图像的背景是白色的。现在,在我的网站上,我想在不同的地方使用不同尺寸的相同图像。问题是,由于图像背景的颜色是白色的。但是,我需要作为缩略图的背景颜色是绿色的。同样,作为主要产品图像,我希望背景呈浅蓝色。例如,这是一张图片。 link。你可以看到这个图像的背景是白色的。我想使用与缩略图相同的图像。我写了一个代码来生成图像缩略图。但我想要一些其他颜色的背景。这可以通过图像处理完成,最好在python中完成? 谢谢。相同图像的不同背景,但大小不同
编辑:我不能评论任何答案吗,不明白为什么。请回复。
答
这很容易做,如果你可以容忍在结果图像中的一些丑陋的影响。如果具有不同背景颜色的此图像将显示为原始图像的缩小版本,则这些效果可能不明显,并且都是好的。
所以这里是一个简单的方法:
- 洪水从像素填充率为(0,0),假设它是背景像素(在你的榜样白色),并进行颜色填充时接受的细微差别。背景像素被透明点所取代。
- 上述步骤提供了一个掩模,例如,您可以执行腐蚀和高斯过滤。
- 用上面创建的蒙版粘贴“充满洪水”的图像。
以下是您可以从这种方法中得到的结果。输入图像,然后两次转换为不同的背景颜色。
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])
他们处理4个图像的透明度 – wim 2013-02-11 06:49:41
这是棘手其实,你需要处理您的链接的图像JPG的工件,还处理这应该是白色的,但不是背景像素。之后,你必须进行一次转变,使其看起来不可怕。我相信我在这个网站上看到过类似的问题,也许有人知道我指的是什么,并且会包含一个链接。 – mmgp 2013-02-11 19:42:33
@mmgp你在想这个吗? http://*.com/questions/8041703/remove-white-background-from-an-image-and-make-it-transparent – 2013-02-11 21:35:11