获取灰度图像
import cv2
#读取图片
img = cv2.imread("picture.bmp", cv2.IMREAD_UNCHANGED)
#灰度图像
p = img[88, 142]
print(p)
#显示图像
cv2.imshow("Demo", img)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
#写入图像
cv2.imwrite("testyxz.jpg", img)
读取像素通道信息
# -*- coding:utf-8 -*-
import cv2
#读取图片
img = cv2.imread("test.jpg", cv2.IMREAD_UNCHANGED)
#BGR图像
b = img[78, 125, 0]
print(b)
g = img[78, 125, 1]
print(g)
r = img[78, 125, 2]
print(r)
#方法二
bgr = img[78, 125]
print(bgr)
#显示图像
cv2.imshow("Demo", img)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
#写入图像
cv2.imwrite("testyxz.jpg", img)
修改像素
# -*- coding:utf-8 -*-
import cv2
#读取图片
img = cv2.imread("test.jpg", cv2.IMREAD_UNCHANGED)
#BGR图像
print(img[78, 125, 0])
print(img[78, 125, 1])
print(img[78, 125, 2])
#修改像素
img[78, 125, 0] = 255
img[78, 125, 1] = 255
img[78, 125, 2] =255
print(img[78, 125])
img[78, 125] = [10, 10, 10]
print(img[78, 125, 0])
print(img[78, 125, 1])
print(img[78, 125, 2])
#方法二
print(img[78, 125])
img[78, 125] = [10, 10, 10]
print(img[78, 125])
赋值块状区域
# -*- coding:utf-8 -*-
import cv2
#读取图片
img = cv2.imread("test.jpg", cv2.IMREAD_UNCHANGED)
#BGR图像
img[100:150, 400:500] = [255, 255, 0]
#显示图像
cv2.imshow("Demo", img)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
#写入图像
cv2.imwrite("testyxz.jpg", img)
NumPy读取数据
# -*- coding:utf-8 -*-
import cv2
import numpy
#读取图片
img = cv2.imread("test.jpg", cv2.IMREAD_UNCHANGED)
#Numpy读取像素
blue = img.item(78, 100, 0)
green = img.item(78, 100, 1)
red = img.item(78, 100, 2)
print(blue)
print(green)
print(red)
#显示图像
cv2.imshow("Demo", img)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
numpy.itemset()
是一个用于精确修改数组中单个元素的工具,尤其适合在需要显式指定索引和值的场景中使用。对于大多数情况,直接通过索引赋值(arr[i] = value)
更简洁,但 itemset()
提供了另一种灵活的操作方式。
# -*- coding:utf-8 -*-
import cv2
import numpy
#读取图片
img = cv2.imread("test.jpg", cv2.IMREAD_UNCHANGED)
#Numpy读取像素
print(img.item(78, 100, 0))
print(img.item(78, 100, 1))
print(img.item(78, 100, 2))
img.itemset((78, 100, 0), 100)
img.itemset((78, 100, 1), 100)
img.itemset((78, 100, 2), 100)
print(img.item(78, 100, 0))
print(img.item(78, 100, 1))
print(img.item(78, 100, 2))