Jos*_* B. 8 python image image-resizing pillow
我正在开展一个项目,我想把彩色网格的图片作为输入(在这个例子中用乐高积木制作)并返回一个小得多的修改图片.
这是一个示例输入:
下面是一个非常小的8x8图像,结果如下:
这是预期结果的更大版本:
这是我目前的代码: 它只适用于黑白图像.
from PIL import Image
import re
black = [(110,110,110),(0,0,0)] #The highest value and the lowest RGB value for the color black
img = Image.open("input.jpg") #The input image
size = (8,8) #The dimensions of the output image
out = img.resize(size,resample=Image.LANCZOS) #Resize the image
for y in range(size[0]): #loop through every pixel
for x in range(size[1]):
if out.getpixel((x,y)) <= black[0] and out.getpixel((x,y)) >= black[1]: #check to see if the pixel is within the accepted black values
out.putpixel((x,y), (0,0,0)) #Give the current pixel true color
else:
#otherwise make the pixel black
out.putpixel((x,y), (255,255,255)) #Give the current pixel true color
"""Save the pixelated image"""
out.save("output.jpg")
Run Code Online (Sandbox Code Playgroud)
并且我的代码返回了输出:
我的程序适用于黑白图像,但我需要帮助改变它以使用几种颜色(红色,橙色,黄色,浅绿色,深绿色,浅蓝色,深蓝色,紫色,黑色和白色).
提前致谢!
你做错了几件事.
首先,您应该使用PNG而不是JPG作为输出.JPG引入了如此多的工件,像输出这样的小图像完全退化了.
然后,你应该减少你的调色板.使用不含噪音的输入更容易.
首先,无聊的初始化:
from PIL import Image
import operator
from collections import defaultdict
import re
input_path = 'input.jpg'
output_path = 'output.png'
size = (4,4)
Run Code Online (Sandbox Code Playgroud)
然后我们声明调色板 - 这应该包含所有可能的乐高积木的颜色.我从您的图像中采样了下面的值,但您可以像在代码中使用黑色和白色一样使用黑色和白色,或者只要它们与源图像中的颜色相似,就可以使用您想要的任何颜色:
palette = [
(45, 50, 50), #black
(240, 68, 64), #red
(211, 223, 223), #white
(160, 161, 67), #green
(233, 129, 76), #orange
]
while len(palette) < 256:
palette.append((0, 0, 0))
Run Code Online (Sandbox Code Playgroud)
下面的代码将为PIL声明调色板,因为PIL需要平面数组而不是元组数组:
flat_palette = reduce(lambda a, b: a+b, palette)
assert len(flat_palette) == 768
Run Code Online (Sandbox Code Playgroud)
现在我们可以声明一个包含调色板的图像.我们稍后会用它来减少原始图像的颜色.
palette_img = Image.new('P', (1, 1), 0)
palette_img.putpalette(flat_palette)
Run Code Online (Sandbox Code Playgroud)
在这里,我们打开图像并量化它.我们将它缩放到比需要大8倍的尺寸,因为我们将在稍后对平均输出进行采样.
multiplier = 8
img = Image.open(input_path)
img = img.resize((size[0] * multiplier, size[1] * multiplier), Image.BICUBIC)
img = img.quantize(palette=palette_img) #reduce the palette
Run Code Online (Sandbox Code Playgroud)
在此之后,我们的图像如下所示:
我们需要将其转换回RGB,以便我们现在可以采样像素:
img = img.convert('RGB')
Run Code Online (Sandbox Code Playgroud)
现在我们要构建我们的最终图像.为此,我们将采样较大图像中每个方块包含的每种调色板颜色的像素数.然后我们将选择最常出现的颜色.
out = Image.new('RGB', size)
for x in range(size[0]):
for y in range(size[1]):
#sample at get average color in the corresponding square
histogram = defaultdict(int)
for x2 in range(x * multiplier, (x + 1) * multiplier):
for y2 in range(y * multiplier, (y + 1) * multiplier):
histogram[img.getpixel((x2,y2))] += 1
color = max(histogram.iteritems(), key=operator.itemgetter(1))[0]
out.putpixel((x, y), color)
Run Code Online (Sandbox Code Playgroud)
最后,我们保存输出:
out.save(output_path)
Run Code Online (Sandbox Code Playgroud)
结果:
上调1600%:
归档时间: |
|
查看次数: |
3055 次 |
最近记录: |