# python opencv读取图像像素值_Python 图像处理 OpenCV （2）：像素处理与 Numpy 操作以及 Matplotlib 显示图像...

1. 读取像素

import cv2 as cv

# 灰度图像读取

print(gray_img[20, 30])

# 显示图片

cv.imshow("gray_img", gray_img)

# 等待输入

cv.waitKey()

cv.destroyAllWindows()

import cv2 as cv

# 彩色图像读取

print(color_img[20, 30])

blue = color_img[20, 30, 0]

print(blue)

green = color_img[20, 30, 1]

print(green)

red = color_img[20, 30, 2]

print(red)

# 显示图片

cv.imshow("color_img", color_img)

# 等待输入

cv.waitKey()

cv.destroyAllWindows()

# 打印结果

[ 3 2 236]

3

2

236

2. 修改像素

import cv2 as cv

# 灰度图像读取

print(gray_img[20, 30])

# 像素赋值

gray_img[20, 30] = 255

print(gray_img[20, 30])

# 打印结果

72

255

# 彩色图像读取

print(color_img[20, 30])

# 像素依次赋值

color_img[20, 30, 0] = 255

color_img[20, 30, 1] = 255

color_img[20, 30, 2] = 255

print(color_img[20, 30])

# 打印结果

[ 3 2 236]

[255 255 255]

# 像素一次赋值

color_img[20, 30] = [0, 0, 0]

print(color_img[20, 30])

# 打印结果

[0 0 0]

import cv2 as cv

color_img[50:100, 50:100] = [255, 255, 255]

cv.imshow("color_img", color_img)

cv.waitKey()

cv.destroyAllWindows()

1. 读取像素

import cv2 as cv

# 读取灰度图像

print(gray_img.item(20, 30))

# 打印结果

72

# 读取彩色图像

blue = color_img.item(20, 30, 0)

print(blue)

green = color_img.item(20, 30, 1)

print(green)

red = color_img.item(20, 30, 2)

print(red)

# 打印结果

3

2

236

2. 修改像素

import cv2 as cv

# 读取彩色图像

print(color_img[20, 30])

color_img.itemset((20, 30, 0), 255)

color_img.itemset((20, 30, 1), 255)

color_img.itemset((20, 30, 2), 255)

print(color_img[20, 30])

# 输出结果

[ 3 2 236]

[255 255 255]

Matplotlib 显示图像

import cv2 as cv

from matplotlib import pyplot as plt

plt.imshow(img)

plt.show()

import cv2 as cv

from matplotlib import pyplot as plt

# method1

b,g,r=cv.split(img)

img2=cv.merge([r,g,b])

plt.imshow(img2)

plt.show()

# method2

img3=img[:,:,::-1]

plt.imshow(img3)

plt.show()

# method3

img4=cv.cvtColor(img, cv.COLOR_BGR2RGB)

plt.imshow(img4)

plt.show()

04-16

07-25
02-24
03-29 116
10-29 2万+
07-22 693
08-02 1453
11-28 1867
09-11 48
10-24 394
06-15 1万+