这篇“Python如何获取图片像素BGR值并生成纯色图”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python如何获取图片像素BGR值并生成纯色图”文章吧。
需要使用opencv以及numpy。安装命令如下:
pip install opencv-python -i https://pypi.douban.com/simple pip install numpy -i https://pypi.douban.com/simple
不废话,上代码。
#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@author : 剑客阿良_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
# 获取图片坐标bgr值
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
# 构建纯色图
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)
# 创建BGR纯色图
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)))
代码说明:
1、get_pix_bgr方法入参分别为,图片地址以及坐标位置,用以获取bgr值。
2、make_one_color_pic方法为最终生成纯色图方法,参数有输出目录地址、图片地址、坐标位置、最终图片分辨率,输出最终图片路径。
3、最终图片名使用uuid,避免重复。
4、做了简单的文件后缀校验,如需修改,可以自己添加。
准备的图片
执行结果
最终的图片
以上就是关于“Python如何获取图片像素BGR值并生成纯色图”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。