国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python用61行代碼實(shí)現(xiàn)圖片像素化的示例代碼

2020-02-16 00:02:55
字體:
供稿:網(wǎng)友

起因

看到網(wǎng)上的像素圖片,感覺蠻有趣的,就打算用python一些PIL類庫寫一個。

實(shí)現(xiàn)思路

把一張圖片分成多個塊,每個塊的顏色都等于這個色塊中顏色最多的顏色,如下圖。


這個圖取2×2的像素為塊的大小,把快中顏色與每個顏色出現(xiàn)的數(shù)量存放到字典里,取最大的顏色,填充整個塊。

具體實(shí)現(xiàn)

from PIL import Imagedef init():  # 設(shè)置每個像素區(qū)塊的大小  block_size = 75  img = Image.open("a.jpg")  # 獲取圖片的寬高  width, height = img.size  # 獲取像素點(diǎn)對應(yīng)RGB顏色值,可以改變img_array中的值來改變顏色值  img_array = img.load()  # 為了處理最后的區(qū)塊,加了一次循環(huán)  max_width = width + block_size  max_height = height + block_size  for x in range(block_size - 1, max_width, block_size):    for y in range(block_size - 1, max_height, block_size):      # 如果是最后一次循環(huán),則x坐標(biāo)等于width - 1      if x == max_width - max_width % block_size - 1:        x = width - 1      # 如果是最后一次循環(huán),則x坐標(biāo)等于height - 1      if y == max_height - max_height % block_size - 1:        y = height - 1      # 改變每個區(qū)塊的顏色值      change_block(x, y, block_size, img_array)      y += block_size    x += block_size  img.save(r'D:/python/pixel_image/awesome_copy.png')  img.show()""":param x坐標(biāo) x: :param y坐標(biāo) y: :param 區(qū)塊大小 black_size: :param 可操作圖片數(shù)組 img_array: """def change_block(x, y, black_size, img_array):  color_dist = {}  block_pos_list = []  for pos_x in range(-black_size + 1, 1):    for pos_y in range(-black_size + 1, 1):      # todo print(x + pos_x,y + pos_y)      block_pos_list.append([x + pos_x, y + pos_y])  for pixel in block_pos_list:    if not str(img_array[pixel[0], pixel[1]]) in color_dist.keys():      color_dist[str(img_array[pixel[0], pixel[1]])] = 1    else:      color_dist[str(img_array[pixel[0], pixel[1]])] += 1  # key-->value => value-->key  new_dict = {v: k for k, v in color_dist.items()}  max_color = new_dict[max(color_dist.values())]  # 將區(qū)塊內(nèi)所有的顏色值設(shè)置為顏色最多的顏色  for a in block_pos_list:    img_array[a[0], a[1]] = tuple(list(map(int, max_color[1:len(max_color) - 1].split(","))))def get_key(dict, value):  return [k for k, v in dict.items() if v == value]if __name__ == "__main__":  init()

效果對比


總結(jié)

開源地址https://github.com/MasakiOvO/pixel_image

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 全南县| 车致| 宁都县| 班玛县| 西安市| 汝城县| 佛教| 曲阜市| 安吉县| 安图县| 安岳县| 安塞县| 临高县| 南安市| 汽车| 锦州市| 江油市| 墨江| 富蕴县| 博乐市| 新乡市| 宣汉县| 南江县| 大渡口区| 太谷县| 溧水县| 政和县| 扎兰屯市| 银川市| 小金县| 故城县| 鄂托克前旗| 西宁市| 乐山市| 龙胜| 滁州市| 龙门县| 万源市| 栾川县| 雷山县| 兖州市|