Python 官方文档:入门教程 => 点击学习
这篇“python如何获取图片像素BGR值并生成纯色图”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python如何获取图片
这篇“python如何获取图片像素BGR值并生成纯色图”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python如何获取图片像素BGR值并生成纯色图”文章吧。
需要使用OpenCV以及numpy。安装命令如下:
pip install opencv-python -i https://pypi.douban.com/simplepip 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 cv2import osimport numpy as npimport 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)))
代码说明:
get_pix_bgr方法入参分别为,图片地址以及坐标位置,用以获取bgr值。
make_one_color_pic方法为最终生成纯色图方法,参数有输出目录地址、图片地址、坐标位置、最终图片分辨率,输出最终图片路径。
最终图片名使用uuid,避免重复。
做了简单的文件后缀校验,如需修改,可以自己添加。
准备的图片
执行结果
最终的图片
以上就是关于“Python如何获取图片像素BGR值并生成纯色图”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注编程网Python频道。
--结束END--
本文标题: Python如何获取图片像素BGR值并生成纯色图
本文链接: https://www.lsjlt.com/news/306875.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0