preface

Recently, I have a requirement to obtain a pixel color of a picture and generate a solid color picture of that color. So I wrote a tool and shared it with you. If you have the same scene, you can use it directly.

Depend on the installation

Use OpencV as well as Numpy. The installation command is as follows:

pip install opencv-python -i pypi.douban.com/simple

pip install numpy -i pypi.douban.com/simple

code

Cut the crap. Go to the code.

#! /user/bin/env python
# coding=utf-8
"" @project: CSDN @author: Swordman Aliang _ALiang @file: make_pic_tool.py @ide: PyCharm @time: 2022-01-11 08:34:31 ""
import cv2
import os
import numpy as np
import uuid


# get image coordinates BGR value
def get_pix_bgr(image_path: str, x: int, y: int) :
    ext = os.path.basename(image_path).strip().split('. ')[-1]
    if ext not in ['png'.'jpg'] :raise Exception('format error')
    img = cv2.imread(image_path)
    px = img[x, y]
    blue = img[x, y, 0]
    green = img[x, y, 1]
    red = img[x, y, 2]
    return blue, green, red


# Build a solid color map
def make_one_color_pic(output_dir: str, image_path: str, coordinates: tuple, resolution: tuple) :
    blue, green, red = get_pix_bgr(image_path, coordinates[0], coordinates[1])
    img = np.zeros((resolution[1], resolution[0].3), np.uint8)
    # create BGR solid color map
    img[:] = [blue, green, red]
    result_image = os.path.join(output_dir, '{}.jpg'.format(uuid.uuid1().hex))
    cv2.imwrite(result_image, img)
    return result_image


if __name__ == '__main__':
    print(make_one_color_pic(r'C:\Users\huyi\Desktop'.r'C:\Users\huyi\Desktop\2054146.jpg', (300.300), (1080.1920)))
Copy the code


1. Input parameters of get_pix_bgr method are, image address and coordinate position, respectively, to obtain BGR value.

2. The make_one_COLOR_pic method is the method to generate the final pure color map. The parameters include output directory address, image address, coordinate position, final image resolution and output final image path.

3. Use uUID for the final image name to avoid repetition.

4, do a simple file suffix check, if you need to modify, you can add yourself.


verify

Prepared pictures

The execution result

Final picture


conclusion

I am still busy with my work recently, so I will write more if I have time.

Glory is like a river: light and empty glory floats upon its surface, heavy and thick glory at its bottom. — “Essays”

If this article helped you, please give it a thumbs up. Thanks!

My CSDN home page address: Swordsman Aliang’s home page

Learn together and make progress together.