您好,登錄后才能下訂單哦!
這篇“Python如何獲取圖片像素BGR值并生成純色圖”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“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 # 獲取圖片坐標(biāo)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 # 構(gòu)建純色圖 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) # 創(chuàng)建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方法入?yún)⒎謩e為,圖片地址以及坐標(biāo)位置,用以獲取bgr值。
2、make_one_color_pic方法為最終生成純色圖方法,參數(shù)有輸出目錄地址、圖片地址、坐標(biāo)位置、最終圖片分辨率,輸出最終圖片路徑。
3、最終圖片名使用uuid,避免重復(fù)。
4、做了簡單的文件后綴校驗(yàn),如需修改,可以自己添加。
準(zhǔn)備的圖片
執(zhí)行結(jié)果
最終的圖片
以上就是關(guān)于“Python如何獲取圖片像素BGR值并生成純色圖”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。