Less than 100 lines of code Python to make a Jiugongge picture generator, cool circle of friends!

This kind of picture arrangement style below the circle of friends will be familiar to everyone, and there is something about job recruitment

Snipaste_2020-08-02_19-48-58.png

Congratulations,

Snipaste_2020-08-02_19-49-57.png

Sifting your own beautiful photos,

Snipaste_2020-08-02_19-51-37.png

Because the picture is arranged in a 3*3 format, it is called a 9-grid picture style. The principle of picture generation is to divide a picture into 9 fragments in equal proportions by area. You only need to post it by yourself when you are in the circle of friends. Just adjust the placement of the picture fragments.

Although the principle of making 9 square grids is relatively simple, its addition makes the dynamic of only one picture in the circle of friends visually improved to a level

Next, this article will introduce how to use Python to convert a picture into a 9-square grid, and add a GUI interface to package it into a program. Let’s take a look at the preview effect of the program:

Recording_2020_08_02_19_41_58_289.gif

The environment configuration produced this time is introduced as follows:

  • Python 3.7;
  • Opencv: 3.4;
  • PyQt5: 5.9;

Production steps

First, let’s first convert the basic idea of ​​Jiugongge picture conversion:

  • 1. Turn the picture into a square first, and fill the insufficient sides with white pixels;
  • 2. Find the three equidistant distances of the picture, divide the picture into 9 areas in the for recursive form, and store them as a list, because the pictures here are represented in the form of an array, so they are well divided according to the array form;
  • 3. Store the list of pictures obtained by dividing 2 separately, and use the file name for numbering;

The core code is as follows:

 if self.open_file_path and self.save_file_path:
            try:
                img = cv2.imread(self.open_file_path)
                if len(img.shape) == 2: # 判断是否为灰度图
                    last_dim = 1
                else:
                    last_dim = 3
                if img.shape[0] != img.shape[1]:
                    # 长宽不一致
                    new_image = np.zeros((max(img.shape), max(img.shape), last_dim), dtype=np.uint8) + 255
                    # 图像填充
                    new_image[
                    int((new_image.shape[0] - img.shape[0]) / 2):img.shape[0] + int((new_image.shape[0] - img.shape[0]) / 2),
                    int((new_image.shape[1] - img.shape[1]) / 2):img.shape[1] + int((new_image.shape[1] - img.shape[1]) / 2),:] = img
                else:
                    new_image = img
                # 开始进行图像分割
                col_width = int(new_image.shape[0] / 3)

                # 得到九宫格图像
                image_list = [new_image[i * col_width:(i + 1) * col_width, j * (col_width):(j + 1) * col_width, :] for i in
                              range(3) for j in range(3)]
                for i in range(9):
                    image_name = str(i)
                    save_image_path = os.path.join(self.save_file_path, f'{image_name}.png')
                    cv2.imwrite(save_image_path, np.array(image_list[i]))
                    print(f'save {image_name} sucessfully!')
                QMessageBox.information(self,'info','转换完成!')
            except Exception as e:
                print(e)
                QMessageBox.warning(self,'error',f'转换失败{str(e)}')
        else:
            QMessageBox.information(self,'err','文件为空,请重新操作')

GUI encapsulation

The second part is GUI encapsulation. Here I use PyQt5 to create a QWidgt component, place three buttons, and two LineEdit, a total of 5 components, because there are no attributes (color, background, interactive effects) set, and no layout. So the program is relatively simple

Snipaste_2020-08-02_20-31-59.png

In the program, the interface is also added to some unusual information processing, such as opening address is empty, the conversion fails, the program will give a prompt, such as the following that, in the absence of click Select Folder to start the conversion button , given Error message

Snipaste_2020-08-02_20-39-06.png

The main code part of the GUI interface:

    def open_origin_file(self):
        open_file = QFileDialog.getOpenFileName(None,"Open File","C:/","Image (*.png)")
        if open_file[0]:
            print(open_file[0])
            self.open_file_path = open_file[0]
            self.line_edit.setText(self.open_file_path)
        else:
            QMessageBox.warning(self,"info","Fail to open file, please try it again!")

    def save_file(self):

        open_file = QFileDialog.getExistingDirectory(None,'Open File','C:/')
        if open_file:
            print(open_file)
            self.save_file_path = open_file
            self.line_edit1.setText(str(self.save_file_path))
        else:
            QMessageBox.warning(self,'info','Fail to open file, Please try it again!')

Here I found a picture to test this small program, the picture is an anime character-Pikachu, the effect is as follows,

Snipaste_2020-08-02_20-55-46.png

Finally, I randomly found a picture and sent it to the circle of friends. The result is the second picture below (the original picture is the first). Objectively speaking, the visual effect of a single picture has not improved. The main reason is The ratio of length, width and height of the original image is inconsistent, that is to say, for some images with inconsistent length and width, it is better to crop the image before converting it into Jiugongge, otherwise it is not suitable for conversion into Jiugongge

Original image

1.png

Directly converted images without cropping

WeChat Picture_20200807235727.jpg

Converted image after cropping

WeChat image_20200808001007.jpg

After cutting the converted visual effects have improved significantly, small partners are also interested to try, full source code on the article, Mr. public No. [Z] background points in mind reply squares can get.

Okay, the above is all the content of this article, and thank you all for reading!

Guess you like

Origin blog.csdn.net/weixin_42512684/article/details/107904375