# USAGE
# python opencv_getting_setting.py --image fjdj.png
# 導(dǎo)入必要的包
import argparse
import cv2
import imutils
import numpy as np
# 構(gòu)建命令行參數(shù)及解析
# --image 磁盤圖片路徑,默認(rèn)名稱為當(dāng)前py文件同級(jí)目錄:fjdj.jpg
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", type=str, default="fjdj.jpg",
help="path to the input image")
args = vars(ap.parse_args())
ap = argparse.ArgumentParser()
# 加載圖像,獲取空間維度(寬度、高度),展示原始圖像到屏幕
image = cv2.imread(args["image"])
image = imutils.resize(image, width=430)
origin = image.copy()
(h, w) = image.shape[:2]
cv2.imshow("Original", image)
# 圖像以Numpy數(shù)組存在,獲取左上角,圖像索引從0開始
# 圖像以BGR通道表示,因?yàn)樽铋_始BGR是標(biāo)準(zhǔn),后來調(diào)整為RGB
(b, g, r) = image[0, 0]
print("Pixel at (0, 0) - Red: {}, Green: {}, Blue: {}".format(r, g, b))
# 獲取x=380,y=380的像素值,圖像想象為M*N的矩陣,M為行,N為列
(b, g, r) = image[380, 380]
print("Pixel at (380, 380) - Red: {}, Green: {}, Blue: {}".format(r, g, b))
# 更新x=50,y=20的像素為紅色
image[380, 380] = (0, 0, 255)
(b, g, r) = image[380, 380]
print("Pixel at (380, 380) - Red: {}, Green: {}, Blue: {}".format(r, g, b))
# 計(jì)算圖像的中心
(cX, cY) = (w // 2, h // 2)
# 使用數(shù)組切片獲取左上角1/4的部分
tl = image[0:cY, 0:cX]
cv2.imshow("Top-Left Corner", tl)
# 同樣的,用數(shù)組切片裁剪 右上角、左下角、右下角部分,并展示
tr = image[0:cY, cX:w]
br = image[cY:h, cX:w]
bl = image[cY:h, 0:cX]
cv2.imshow("Top-Right Corner", tr)
cv2.imshow("Bottom-Right Corner", br)
cv2.imshow("Bottom-Left Corner", bl)
# 使用像素切片來更改像素區(qū)域的顏色
image[0:cY, 0:cX] = (0, 255, 0)
# 展示更新像素后的圖片
cv2.imshow("Updated (Top-Left Corner to Green)", image)
gray = cv2.cvtColor(origin, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
(h, w) = origin.shape[:2]
zeros = np.zeros((h, w), dtype="uint8")
# 將origin分離為紅色,綠色和藍(lán)色通道, 然后我們使用Numpy 零數(shù)組分別構(gòu)造每個(gè)通道的表示形式
(B, G, R) = cv2.split(origin)
R = cv2.merge([zeros, zeros, R])
G = cv2.merge([zeros, G, zeros])
B = cv2.merge([B, zeros, zeros])
cv2.imshow("B G R", np.hstack([B, G, R]))
# 構(gòu)建輸出幀 原圖在左上角 紅色通道右上角 綠色通道右下角 藍(lán)色通道左下角
output = np.zeros((h * 2, w * 2, 3), dtype="uint8")
output[0:h, 0:w] = origin
output[0:h, w:w * 2] = R
output[h:h * 2, 0:w] = G
output[h:h * 2, w:w * 2] = B
cv2.imshow("origin vs R vs G vs B", imutils.resize(output, width=700))
alpha0 = np.dstack([origin, np.ones((h, w), dtype="uint8") * 0])
cv2.imshow("alph 0", alpha0)
cv2.imwrite("alph 0.png", alpha0)
alpha1 = np.dstack([origin, np.ones((h, w), dtype="uint8") * 255])
cv2.imshow("alph 255", alpha1)
cv2.imwrite("alph 255.png", alpha1)
cv2.waitKey(0)
到此這篇關(guān)于超詳細(xì)注釋之OpenCV更改像素與修改圖像通道的文章就介紹到這了,更多相關(guān)OpenCV 像素 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!