OpenCV Python 如何访问和修改图像中的像素值

OpenCV Python 如何访问和修改图像中的像素值

要访问图像中的单个像素值,我们可以使用与NumPy数组索引相同的索引。我们可以使用切片来访问一系列像素值。要修改像素值,我们使用简单的Python赋值运算符(”=”)。

步骤

要访问和修改图像中的像素值,可以按照以下步骤进行:

  • 导入所需的库。在以下所有示例中,所需的Python库是 OpenCV 。确保您已经安装了它。

  • 使用 cv2.imread() 读取输入的 RGB 图像。使用此方法读取的RGB图像是以BGR格式存储的。可选择将读取的BGR图像赋值给img。

  • 要访问单个像素,使用索引;要修改单个像素值,使用索引赋值。例如,要将[200,150]位置的像素值修改为红色,我们可以应用以下操作:

img[200,150] = (0, 0, 255)
  • 访问像素序列使用切片,修改这些像素值使用切片赋值。例如,要将[100:300, 150:350]处的像素值修改为红色,我们应用以下操作:
img[100:300,150:350] = (0, 0, 255)

我们将在以下示例中使用此图像作为 输入文件

OpenCV Python 如何访问和修改图像中的像素值

示例

在这个Python程序中,我们访问输入图像中某一点的像素值。我们还找出了三个不同颜色通道的像素值,并修改了该点的红色通道的像素值。

# program to access and modify a pixel value

# import required libraries
import cv2

# read the input image
img = cv2.imread('horizon.jpg')

# access pixel values using indexing
print("pixel value at [200,150]:", img[200,150])
print("pixel value blue channel at [200,150]:", img[200,150][0])
print("pixel value green channel at [200,150]:", img[200,150][1])
print("pixel value red channel at[200,150]:", img[200,150][2])

# modify the pixel value at [200,150] for red color channel
img[200,150] = (0, 0, 255)
print("after modifying pixel value at [200,150]:", img[200,150])

输出

当你运行上面的程序时,它会产生以下输出结果−

pixel value at [200,150]: [115 192 254]
pixel value blue channel at [200,150]: 115
pixel value green channel at [200,150]: 192
pixel value red channel at [200,150]: 254
after modifying pixel value at [200,150]: [ 0 0 255]

示例

在这个Python程序中,我们访问输入图像中一个区域的像素值。我们还将这些像素值修改为红色。

# program to access and modify the pixel values of a region

# import required libraries
import cv2

# read the input image
img = cv2.imread('horizon.jpg')

# access pixel values using indexing and slicing

# modify pixel color of a region to red color
img[100:300,150:350] = (0, 0, 255)

# display the modified image
cv2.imshow('Modified Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

输出

当你运行上面的程序时,它会产生以下输出-

OpenCV Python 如何访问和修改图像中的像素值

注意在修改像素值为红色后的输出图像。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程