First look at the effect:

Basic idea: Fill thin colored pixels randomly on a black background

Main process:

  • Start by creating a 512 x 512 canvas with an opaque solid black background
  • Pixel m is randomly selected from 512 x 512 pixels with a certain probability
  • The color of pixel M is randomly selected from 7 preset colors (red, orange, yellow, green, cyan, blue, violet)

1. Install the Python library

pip install pillow
Copy the code

2. Create the RGBA image canvas with the background color set to opaque solid black

from PIL import Image
width = 512
height = 512
The image size is 512x512
img = Image.new('RGBA', (width, height), (0.0.0.255))
Copy the code

3. Randomly select 3% of pixels to turn into color

# set the probability of picking a point 0.03 = 3%
percent = 0.03
Walk through all pixels of the 512x512 image
for i in range(512) :for j in range(512) :# Because random. Random () produces random numbers that are evenly distributed between 0 and 1
        Random () produces a random value between 0 and percent to change the color
        if random.random() <= percent:
            # Select a random color from the preset colors list
            rgba = random.choice(colors)
            # Set the coordinate color
            img.putpixel((j, i), rgba)
Copy the code

4. Save the picture

img.save('c.png'.'PNG')
print("Ha ha, the colorful black is done!")
img.show()
Copy the code

The final complete code is as follows

#! /bin/env python
# coding: utf-8
# author: ZhangTao
# Date : 2019/12/12
# Colorful Black

from PIL import Image
import random

width = 512
height = 512
The image size is 512x512
img = Image.new('RGBA', (width, height), (0.0.0.255))

# Preset 7 colors, then randomly generate pixel color to be used
colors = [
    # red
    (255.0.0.255),
    # orange
    (255.128.0.255),
    # yellow
    (255.255.0.255),
    # green
    (0.255.0.255),
    # green
    (0.255.255.255),
    # blue
    (0.0.255.255),
    # purple
    (128.0.255.255)]# set the probability of picking a point 0.03 = 3%
percent = 0.03
Walk through all pixels of the 512x512 image
for i in range(512) :for j in range(512) :# Because random. Random () produces random numbers that are evenly distributed between 0 and 1
        Random () produces a random value between 0 and percent to change the color
        if random.random() <= percent:
            # Select a random color from the preset colors list
            rgba = random.choice(colors)
            # Set the coordinate color
            img.putpixel((j, i), rgba)

img.save('c.png'.'PNG')
print("Ha ha, the colorful black is done!")
img.show()
Copy the code