# USAGE
# python opencv_getting_setting.py --image fjdj.png
# 导入必要的包
import argparse
import cv2
import imutils
import numpy as np
# 构建命令行参数及解析
# --image 磁盘图片路径,默认名称为当前py文件同级目录: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数组存在,获取左上角,图像索引从0开始
# 图像以BGR通道表示,因为最开始BGR是标准,后来调整为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))
# 计算图像的中心
(cX, cY) = (w // 2, h // 2)
# 使用数组切片获取左上角1/4的部分
tl = image[0:cY, 0:cX]
cv2.imshow("Top-Left Corner", tl)
# 同样的,用数组切片裁剪 右上角、左下角、右下角部分,并展示
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)
# 使用像素切片来更改像素区域的颜色
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分离为红色,绿色和蓝色通道, 然后我们使用Numpy 零数组分别构造每个通道的表示形式
(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]))
# 构建输出帧 原图在左上角 红色通道右上角 绿色通道右下角 蓝色通道左下角
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)
到此这篇关于超详细注释之OpenCV更改像素与修改图像通道的文章就介绍到这了,更多相关OpenCV 像素 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!