How to draw a nice picture with code

foreword

With the gradual development of computer technology, it has become very easy to perform painting operations with the powerful capabilities of computers. The level of painting works is also getting higher and higher. Let's take a look at what interesting things can be created by painting with programming languages, and what are the things worth thinking about compared to human creation.

painting

The most primitive way to output something similar to painting with code is to use the print function directly.

print output characters

def do_print():
    print('''

        へ     /|
      /\7    ∠_/
      / │   / /
     │ Z _,< /   /`ヽ
     │     ヽ   /  〉
      Y     `  /  /
     イ● 、 ●  ⊂⊃〈  /
     ()  へ    | \〈
      >ー 、_  ィ  │ //
      / へ   / ノ<| \\
      ヽ_ノ  (_/  │//
      7       |/
      >―r ̄ ̄`ー―_
     ''')

After this method is executed, you can see the following cute Pikachu painting on the console.

Please add image description

This approach can be said to have no technical level at all. If you want to draw something, you have to arrange the characters in advance, which is too troublesome. So there is an updated version.

Image to character

This kind of converting pictures to characters may seem meaningless, but in fact, sometimes unexpected works can be created. For example, the top stream ice pier a while ago.

Please add image description

In general, the idea of ​​​​this approach is to take the pixel information of the sampled picture of the picture, and then print the key brightness information in the pixel information with a special string, and the effect is what we finally see.

public static void printImage(BufferedImage image) throws IOException {
    
    
    final char[] PIXEL_CHAR_ARRAY = {
    
    'W', '@', '#', '8', '&', '*', 'o', ':', '.', ' '};
    int width = image.getWidth();
    int height = image.getHeight();
    for (int i = 0; i < height; i++) {
    
    
        for (int j = 0; j < width; j++) {
    
    
            int rgb = image.getRGB(j, i);
            Color color = new Color(rgb);
            int red = color.getRed();
            int green = color.getGreen();
            int blue = color.getBlue();
            // 一个用于计算RGB像素点灰度的公式
            Double grayscale = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
            double index = grayscale / (Math.ceil(255 / PIXEL_CHAR_ARRAY.length) + 0.5);
            System.out.print(PIXEL_CHAR_ARRAY[(int)(Math.floor(index))]);
        }
        System.out.println();
    }
}

For more specific implementation, please refer to Character Painting, I used the character to draw a ice dimple .

Drawing using the Python-turtle library

The following few Zhihu users' answers can be said to be very high-level.

import random
import turtle
from turtle import *

t = turtle.Turtle()
w = turtle.Screen()


def tree(branchLen, t):
    if branchLen > 3:
        if 8 <= branchLen <= 12:
            if random.randint(0, 2) == 0:
                t.color('snow')
            else:
                t.color('lightcoral')
            t.pensize(branchLen / 3)
        elif branchLen < 8:
            if random.randint(0, 1) == 0:
                t.color('snow')
            else:
                t.color('lightcoral')
            t.pensize(branchLen / 2)
        else:
            t.color('sienna')
            t.pensize(branchLen / 10)

        t.forward(branchLen)
        a = 1.5 * random.random()
        t.right(20 * a)
        b = 1.5 * random.random()
        tree(branchLen - 10 * b, t)
        t.left(40 * a)
        tree(branchLen - 10 * b, t)
        t.right(20 * a)
        t.up()
        t.backward(branchLen)
        t.down()


def petal(m, t):  # 树下花瓣
    for i in range(m):
        a = 200 - 400 * random.random()
        b = 10 - 20 * random.random()
        t.up()
        t.forward(b)
        t.left(90)
        t.forward(a)
        t.down()
        t.color("lightcoral")
        t.circle(1)
        t.up()
        t.backward(a)
        t.right(90)
        t.backward(b)


def main():
    t = turtle.Turtle()
    myWin = turtle.Screen()
    getscreen().tracer(5, 0)
    turtle.screensize(bg='wheat')
    t.left(90)
    t.up()
    t.backward(150)
    t.down()
    t.color('sienna')
    tree(60, t)
    petal(100, t)

    myWin.exitonclick()


if __name__ == '__main__':
    main()


As you can see, using the turtle library with a strong knowledge of mathematical geometry, you can create very nice looking images. For more information, please refer to this question

Painting with AI

ERNIE-ViLG Vincent Chart

The content drawn using the above scheme is generally more rigid and lacks some humanistic flavor. Missing some of the characteristics that humans can only have. However, with the improvement of AI computing power and the gradual development of big data, there are already many platforms that can use AI for painting. For example, Baidu Feizo Wenxin large model ERNIE-ViLG Wenshengtu platform.

import wenxin_api
from wenxin_api.tasks.text_to_image import TextToImage
import secret


def draw(t, s):
    wenxin_api.ak = secret.ak
    wenxin_api.sk = secret.sk
    input_dict = {
    
    
        "text": t,
        "style": s
    }
    rst = TextToImage.create(**input_dict)
    print(rst)


if __name__ == '__main__':
    text = "夏天"
    style = "油画"
    draw(text, style)

Using the above code, you can create an oil painting style summer , you can see the AI ​​generated results.

2022-08-28 12:20:06,785 - model is painting now!, 
- taskId: 1062408, waiting: 30s
{
    
    'imgUrls': ['https://wenxin.baidu.com/younger/file/ERNIE-ViLG/89df26b9853d837d331d626ffa62828fex', 'https://wenxin.baidu.com/younger/file/ERNIE-ViLG/89df26b9853d837d331d626ffa62828fi4', 'https://wenxin.baidu.com/younger/file/ERNIE-ViLG/89df26b9853d837d331d626ffa62828f5q', 'https://wenxin.baidu.com/younger/file/ERNIE-ViLG/89df26b9853d837d331d626ffa62828f30', 'https://wenxin.baidu.com/younger/file/ERNIE-ViLG/89df26b9853d837d331d626ffa62828fv9', 'https://wenxin.baidu.com/younger/file/ERNIE-ViLG/89df26b9853d837d331d626ffa62828fa2']}

It can be seen that the speed is still very fast and it will be done in less than a minute. You can preview the result






It can be seen that it is still very powerful, and the level should be able to catch up with the graduates of junior colleges, but the speed of painting is a dimensionality reduction blow.

Using ERNIe-ViLG with custom keywords can generate pictures in various styles such as watercolor, oil painting, chalk painting, cartoon, crayon painting, children's painting and so on.

You can try the Tianlong Babu in the watercolor style again .






Is it still a feeling.

FROM AND 2

Of course, when it comes to AI painting, there are also big foreign companies. Such as OpenAI 's DALL·E 2 .

For example, create an image of an astronaut riding a horse in a realistic style

Please add image description

changing pencil drawing style

Please add image description

Using DALL·E 2, you can create very imaginative works by AI according to the creative style and more keywords. You can go to the DALL·E 2 homepage for more details.

Summarize

In fact, using code to draw graphics directly, there are many other solutions. For example, the famous MATLAB can create very sophisticated mathematical geometry.

But comparing the above schemes, it can be said that the level of AI painting has improved several levels at once. The input required for creation is becoming more and more clear, more concise, and more humanized. However, the content of the output has begun to approach or even surpass the level of human beings.

Reference documentation

Guess you like

Origin blog.csdn.net/TOYOTA11/article/details/126575202