不久前,我希望使任意背景颜色透明并开发了这个脚本。它采用图像中最流行的(背景)颜色并创建一个透明度与与背景颜色的距离成正比的 alpha 蒙版。获取 RGB 颜色空间距离对于大图像来说是一个昂贵的过程,所以我尝试使用 numpy 和快速整数 sqrt 逼近操作进行一些优化。首先转换为 HSV 可能是正确的方法。如果你还没有解决你的问题,我希望这会有所帮助:
from PIL import Image
import sys, time, numpy
fldr = r'C:\python_apps'
fp = fldr+'\\IMG_0377.jpg'
rz = 0 # 2 will halve the size of the image, etc..
# ----------------
im = Image.open(fp)
if rz:
w,h = im.size
im = im.resize((w/rz,h/rz))
w,h = im.size
h = im.histogram()
rgb = r0,g0,b0 = [b.index(max(b)) for b in [ h[i*256:(i+1)*256] for i in range(3) ]]
def isqrt(n):
xn = 1
xn1 = (xn + n/xn)/2
while abs(xn1 - xn) > 1:
xn = xn1
xn1 = (xn + n/xn)/2
while xn1*xn1 > n:
xn1 -= 1
return xn1
vsqrt = numpy.vectorize(isqrt)
def dist(image):
imarr = numpy.asarray(image, dtype=numpy.int32) # dtype=numpy.int8
d = (imarr[:,:,0]-r0)**2 + (imarr[:,:,1]-g0)**2 + (imarr[:,:,2]-b0)**2
d = numpy.asarray((vsqrt(d)).clip(0,255), dtype=numpy.uint8)
return Image.fromarray(d,'L')
im.putalpha(dist(im))
im.save(fldr+'\\test.png')