PIL mosaic 传说中的打码~

新的代码~欢呼

还是homework..这次有点挑战咯
先是各种search,搞掂了ubuntu x64的PIL1.1.7(具体看我另一篇文章)
然后下载pil handbook,自学,不断改进,现在这个版本只是还算靠谱的版本吧..

题目:给个图片,给个矩阵密度,像素化(要求是按小矩形的左上第一个点颜色)
我的版本直接平均了整个色块(抱歉不懂专业术语..)(高端吧!)

# 2013.11.11 by Alex YU
# Aha! still single~
# the alpha layer of the picture can't be ignored!
# (here ignored!)
# Notice: JPEG is a greatly inaccurate format!
# for better experience Do Not Use JPEG (PNG is better~)

import Image
#1 import ImageChops
im = Image.open("/home/tro/test.jpg")
pic_w = im.size[0]
pic_h = im.size[1]
layer = im.split()

def divide(w,h,s):
	boxs = [(x,y,x+s,y+s) for x in range(0,w,s) for y in range(0,h,s)]
	for box in boxs:
		snip = layer[i].crop(box)
		yield snip,box

def avg_clr(p):
	c = list(p.getdata())
	return sum(c)/len(c)

def main():
	global i
	for i in range(3):
		for a in divide(pic_w,pic_h,1):# u can change num
			snip,box = a
			layer[i].paste(avg_clr(snip),box)

	output = Image.merge("RGB",layer)
	output.save("/home/tro/output.png")
#1	dif = ImageChops.difference(im,output)
#1	dif.show()
main()
#
输入图片,,如若侵权contact me!
输入图片,<“RGB”,JPEG,620×340>,如若侵权contact me!
输出图片,
输出图片10×10,<“RGB”,PNG>
输出图片,
输出图片20×20,<“RGB”,PNG>
# 2013.11.12 by Alex YU
# process three bands at one step!

import Image
im = Image.open("/home/tro/b.jpg")

def avg_clr(p):
	c = list(p.getdata())
	b = len(c)
	k = map(sum,zip(*c))# greatest step!
	q = (k[0]/b,k[1]/b,k[2]/b)# need perfected!
	return q

def divide(w,h,s):
	global im
	boxes = [(x,y,x+s,y+s) for x in range(0,w,s) for y in range(0,h,s)]
	for box in boxes:
		snip = im.crop(box)
		im.paste(avg_clr(snip),box)

def main():
	divide(im.size[0],im.size[1],20)# u can change num
	im.show()
#	im.save("/home/tro/output.png")

main()
#
# 2013.11.12 by Alex YU
# process three bands at one step!

import Image
im = Image.open("/home/tro/b.jpg")
(pic_w,pic_h) = im.size

def divide(w,h,s):
	boxes = [(x,y,x+s,y+s) for x in range(0,w,s) for y in range(0,h,s)]
	for box in boxes:
		snip = im.crop(box)
		yield snip,box

def avg_clr(p):
	c = list(p.getdata())
	b = len(c)
	k = map(sum,zip(*c))# greatest step!
	q = (k[0]/b,k[1]/b,k[2]/b)# need perfected!
	return q

def main():
	for a in divide(pic_w,pic_h,20):# u can change num
		snip,box = a
		im.paste(avg_clr(snip),box)
	im.show()
#	im.save("/home/tro/output.png")

main()
#

Ps:
1. #1 是为了测试通道处理的图像(矩形设置为1×1)与原图的差异从而判断图像处理部分代码是否正确
2. 这里暂时使用长宽的公约数,未来可能改个补一个边界的代码
3. 第二个代码和第三个代码同时处理RGB三通道,速度比原始代码快了近一倍,第二个代码在测试平均下来比第三个代码快0.x秒
4. 这里环境是虚拟ubuntu13.04 python2.7 PIL1.1.7

References:
Python PIL 骰子作画的算法 其实是打码 – http://www.douban.com/note/186940605/
骰子作画的算法 python – http://fayaa.com/code/view/24264/
PIL-handbook.pdf

发表评论

电子邮件地址不会被公开。 必填项已用*标注