先看效果:
基本構想:在黑色背景中隨機填充稀薄的彩色像素點
主要流程:
- 先創建 512 x 512的畫布,背景設爲不透明的純黑色
- 再在這個512 x 512 個像素點裏按照一定的概率隨機挑選像素點 m
- 像素點 m 的顏色 從預設的7種顏色(赤橙黃綠青藍紫)中隨機挑選
- 安裝用到的 圖像處理 庫
這裏是 庫 庫 庫,如果還沒有安裝 python 環境, 請自行百度python安裝方法和相應的命令(python pip)添加到環境變量的方法
pip install pillow
- 創建 RGBA 圖像畫布, 背景色設置爲不透明的純黑色
from PIL import Image
width = 512
height = 512
# 圖片大小爲 512x512
img = Image.new('RGBA', (width, height), (0, 0, 0, 255))
- 隨機挑選 3%的像素點變成彩色
# 設定挑選的點概率 0.03 就是3%
percent = 0.03
# 遍歷 512x512 圖像的所有像素點
for i in range(512):
for j in range(512):
# 因爲 random.random() 產生的隨機數是 0到 1 之間均勻分佈的
# 就直接用 random.random()產生隨機值是 0 到 percent之間的就改變顏色
if random.random() <= percent:
# 從預設的colors顏色列表中隨機挑選一個顏色
rgba = random.choice(colors)
# 設定座標顏色
img.putpixel((j, i), rgba)
- 保存圖片
img.save('c.png', 'PNG')
print("哈哈, 五彩斑斕的黑大功告成!")
img.show()
最後完整代碼如下
#!/bin/env python
# coding: utf-8
# author: ZhangTao
# Date : 2019/12/12
# 五彩斑斕的黑
from PIL import Image
import random
width = 512
height = 512
# 圖片大小爲 512x512
img = Image.new('RGBA', (width, height), (0, 0, 0, 255))
# 預設7中顏色,後面隨機生成像素點顏色要用到
colors = [
# 赤
(255, 0, 0, 255),
# 橙
(255, 128, 0, 255),
# 黃
(255, 255, 0, 255),
# 綠
(0, 255, 0, 255),
# 青
(0, 255, 255, 255),
# 藍
(0, 0, 255, 255),
# 紫
(128, 0, 255, 255)
]
# 設定挑選的點概率 0.01 就是1%
percent = 0.01
# 遍歷 512x512 圖像的所有像素點
for i in range(512):
for j in range(512):
# 因爲 random.random() 產生的隨機數是 0到 1 之間均勻分佈的
# 就直接用 random.random()產生隨機值是 0 到 percent之間的就改變顏色
if random.random() <= percent:
# 從預設的colors顏色列表中隨機挑選一個顏色
rgba = random.choice(colors)
# 設定座標顏色
img.putpixel((j, i), rgba)
img.save('c.png', 'PNG')
print("哈哈, 五彩斑斕的黑大功告成!")
img.show()