我正在尝试在python中的照片上创建对角渐变。
我能够创建垂直和水平淡入淡出,但是当一个叠加时会覆盖另一个。我知道为什么,我只是不知道如何解决它。我意识到这里可能有很多没有意义的东西,对Python来说相对较新,只是试图弄清楚。预先感谢!
img = Image.open('Anacapa 011.tif')
img = img.copy()
img.putalpha(150)
width, height = img.size
pixels = img.load()
for y in range (int(0), int(height)):
alpha = 150 - int((height*.50 - y)/height/.3 * 150)
for x in range(width):
pixels[x, y] = pixels[x, y][:3] + (alpha,)
for y in range(y, height):
for x in range(width):
pixels[x, y] = pixels[x, y][:3] + (0,)
img1 = img.copy()
width1, height1 = img.size
pixels1 = img.load()
for x1 in range (int(0), int(width1)):
alpha = 150 - int((x1 - width1*.4)/width1/.3 * 150)
for y1 in range(height1):
pixels1[x1, y1] = pixels1[x1, y1][:3] + (alpha,)
for x1 in range(x1, width1):
for y1 in range(height1):
pixels1[x1, y1] = pixels1[x1, y1][:3] + (0,)
问题出在
img1 = img.copy()
此处,您将创建图像的其他副本,并对其应用第二次淡入淡出。如果要将第二个淡入淡出应用于同一图像,则需要处理同一图像,而不是新图像。
只是一个旁注:您可以通过使用每种淡入淡出方法的函数来改进代码。 (我正在假设您的代码可以正常工作,并且没有仔细检查):
def horizontal_fade(img):
width, height = img.size
pixels = img.load()
for y in range (int(0), int(height)):
alpha = 150 - int((height * 0.5 - y) / height / 0.3 * 150)
for x in range(width):
pixels[x, y] = pixels[x, y][:3] + (alpha,)
for y in range(y, height):
for x in range(width):
pixels[x, y] = pixels[x, y][:3] + (0,)
return img
def vertical_fade(img):
width, height = img.size
pixels = img.load()
for x in range (int(0), int(width)):
alpha = 150 - int((x - width * 0.5) / width / 0.3 * 150)
for y in range(height):
pixels[x, y] = pixels[x, y][:3] + (alpha,)
for x in range(x, width):
for y in range(height):
pixels[x, y] = pixels[x, y][:3] + (0,)
然后运行
img = horizontal_fade(vertical_fade(img))
要执行所需的对角渐变。
顺便说一下,这个结构有很多重复。因此,最好将这两个功能概括为一个。从逻辑上讲,垂直淡入和水平淡入是非常相同的过程,唯一的区别是它们对旋转90度的图像进行操作。这在您的代码中得到了反映,因为这两个函数的唯一区别是,horizontal_fade
首先在height
上(即,在外部循环中)然后在width
上(在内部循环中)进行迭代。与vertical_fade
相反。我们可以利用它来减少代码的重复性:
def fade(img, direction="horizontal"):
if direction not in ["horizontal", "vertical"]:
raise ValueError("direction must be either 'horizontal' or 'vertical'")
# Here, we simply flip `height` and `width` to turn the image by 90
# degree "to the eyes of the following algorithm
if direction == "horizontal":
width, height = img.size
else:
height, width = img.size
pixels = img.load()
for y in range (int(0), int(height)):
alpha = 150 - int((height *.5 - y) / height / 0.3 * 150)
for x in range(width):
pixels[x, y] = pixels[x, y][:3] + (alpha,)
for y in range(y, height):
for x in range(width):
pixels[x, y] = pixels[x, y][:3] + (0,)
return img