图像都是由像素点构成的,图像分类:
1、二值图像(任意一个像素只能是0或1);
2、灰度图像(任意一个像素值都在0~255);
3、RGB图像(任意一个像素是(R,G,B)构成的),但是OpenCV是默认颜色通道是BGR.
这节主要介绍下如何处理图像的像素点.
一、灰度图像
示例:
# -*- coding: utf-8 -*-
# Data: 2023/7/2
import cv2
img = cv2.imread("./1-gray.jpg",cv2.IMREAD_UNCHANGED)
# 获取100行,100列像素点的值
print(img[100,100])
# 修改100行,100列像素点的值
img[100,100] = 255
print(img[100,100])
# 修改10行到100行,50列到100列像素点的值
img[10:100,50:100] = 255
cv2.imshow("img",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:
E:\python\opencv\venv\Scripts\python.exe E:\python\opencv\main.py
200
255
二、彩色图像
示例:
# -*- coding: utf-8 -*-
# Data: 2023/7/2
import cv2
img = cv2.imread("./1-1.jpg",cv2.IMREAD_UNCHANGED)
# 获取100行,100列像素点的值,有三个通道,依次是B、G、R
print(img[100,100])
# 按通道获取像素值
print(img[100,100,0])
print(img[100,100,1])
print(img[100,100,2])
# 修改100行,100列像素点的值
img[100,100] = [255,255,255]
print(img[100,100])
# 按通道设置
img[100,100,0] = 254
img[100,100,1] = 253
img[100,100,2] = 252
print(img[100,100])
# 修改10行到100行,50列到100列像素点的值
img[10:100,50:100] = [255,255,255]
# 按通道设置像素值
# img[10:100,50:100,0] = 255
cv2.imshow("img",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:
E:\python\opencv\venv\Scripts\python.exe E:\python\opencv\main.py
[184 199 208]
184
199
208
[255 255 255]
[254 253 252]
Process finished with exit code 0
除了以上获取和修改像素值的方法,还有另一种方法,就是item和itemset:
示例:
# -*- coding: utf-8 -*-
# Data: 2023/7/2
import cv2
img1 = cv2.imread("./1-1.jpg",cv2.IMREAD_UNCHANGED)
# 彩色图像获取像素值,需要指定通道
print(img1.item(500,500,0))
print(img1.item(500,500,1))
print(img1.item(500,500,2))
# 彩色图像修改像素值
img1.itemset((500,500,0),255)
img1.itemset((500,500,1),255)
img1.itemset((500,500,2),255)
print(img1.item(500,500,0))
print(img1.item(500,500,1))
print(img1.item(500,500,2))
img2 = cv2.imread("./1-gray.jpg",cv2.IMREAD_UNCHANGED)
# 灰度图像获取像素值
print(img2.item(500,500))
# 灰度图像修改像素值
img2.itemset((500,500),255)
print(img2.item(500,500))
运行效果
E:\python\opencv\venv\Scripts\python.exe E:\python\opencv\main.py
167
191
197
255
255
255
190
255
Process finished with exit code 0