cool python projects for beginners

Cool Python Projects For Beginners [Full Course] 2019

In this tutorial we will show you how to use less than 100 lines of code to implement a cool python project.

The cool python project is easy, interesting , and fun.

By convention, we also recorded tutorial videos for this project, step by step, complete the programs. The will be detailed code for your reference in the following tutorial.

Cool Python project principle

Character painting is made up of many characters of different shapes. For example, these characters can be mapped to RGB gray values according to some rules.

In this cool python project, we can map the RGB values of pixels to gray values using the following gray value formula.

gray = 0.2126 * r + 0.7152 * g + 0.0722 * b

And the pixel value of the picture, we can get through the Image package of Python.

It is its key code below:

from PIL import Image

im = Image.open("pic.png")

# key code
rgb_im = im.convert("RGB")

# get RGB value key code
*rgb_im.getpixel((j, i))

All in all, the implementation of this less than 100 code project is divided into three steps.

  • a) Gets the picture parameters passed by the python command line
  • b) Implement a function that passes in the RGB value to return the corresponding mapping character
  • c) Outputs the returned mapping characters to the text

The above principle may be a little rough, but it doesn’t matter, the following will take you to step by step code.

Step 1) Parsing command-line parameters

The argparse package of python can resolve the parameters passed in from the command line.

In addition, we can set some parameters through the argparse package, such as output, width, height, and so on.

Now, follow me, put the code below inside of main.py:

from PIL import Image
import argparse

# get argparse instance
parser = argparse.ArgumentParser()

# define input/out file and output char height/width
parser.add_argument("file")
parser.add_argument("-o", "--output")
parser.add_argument("--width", type=int, default=80)
parser.add_argument("--height", type=int, default=80)

# parse args
args = parser.parse_args()

IMG = args.file

WIDTH = args.width

HEIGHT = args.height

OUTPUT = args.output

# List of characters that can be mapped
ascii_char = list("[email protected]#$%^&*(-=_+~ ")

Step 2) RGB value mapping character

RGB value mapping characters, we can map according to the above principle formula, a few lines of code can be completed.

Continue to write the following code in `main.py`:

def get_char(r, g, b, alpha=256):
    """

    :param r:
    :param g:
    :param b:
    :param alpha:
    :return:
    """
    if alpha == 0:
        return ' '

    length = len(ascii_char)

    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

    unit = (256 + 1) / length

    return ascii_char[int(gray / unit)]

Step 3) Mapping characters output to text

Well, let’s write the entry function, collect the mapped characters one by one and output them into `.txt` file.

Write the following code to the main.py file, this is the last part of the code:

if __name__ == '__main__':
    # open image
    im = Image.open(IMG)

    # set images width, height
    im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
    rgb_im = im.convert('RGB')

    txt = ""

    for i in range(HEIGHT):
        for j in range(WIDTH):
            # map rgb to char
            txt += get_char(*rgb_im.getpixel((j, i)))
        txt += '\n'

    print(txt)

    if OUTPUT:
        with open(OUTPUT, "w") as f:
            f.write(txt)

    else:
        with open("output.txt", 'w') as f:
            f.write(txt)

Summarize

Congratulations! You’ve finished all the code…

Here is the complete code for the file main.py.

from PIL import Image
import argparse

# get argparse instance
parser = argparse.ArgumentParser()

# define input/out file and output char height/width
parser.add_argument("file")
parser.add_argument("-o", "--output")
parser.add_argument("--width", type=int, default=80)
parser.add_argument("--height", type=int, default=80)

args = parser.parse_args()

IMG = args.file

WIDTH = args.width

HEIGHT = args.height

OUTPUT = args.output


ascii_char = list("[email protected]#$%^&*(-=_+~ ")


def get_char(r, g, b, alpha=256):
    """

    :param r:
    :param g:
    :param b:
    :param alpha:
    :return:
    """
    if alpha == 0:
        return ' '

    length = len(ascii_char)

    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

    unit = (256 + 1) / length

    return ascii_char[int(gray / unit)]


if __name__ == '__main__':
    # open image
    im = Image.open(IMG)

    # set images width, height
    im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
    rgb_im = im.convert('RGB')

    txt = ""

    for i in range(HEIGHT):
        for j in range(WIDTH):
            # map rgb to char
            txt += get_char(*rgb_im.getpixel((j, i)))
        txt += '\n'

    print(txt)

    if OUTPUT:
        with open(OUTPUT, "w") as f:
            f.write(txt)

    else:
        with open("output.txt", 'w') as f:
            f.write(txt)

Now, run the code via python main.py picture_file.png, you’ll see a surprise 🍺🍺🍺

Please leave a message below, let me know if this was helpful and if you need any additional explanation.

Cheers!

codingadmin

Leave a Reply

avatar
  Subscribe  
Notify of