Opencv Python 简明教程

OpenCV Python - Image Properties

OpenCV 会在 NumPy 数组中读取图像数据。此 ndarray 对象的 shape() 方法揭示了图像属性,例如维度和通道。

OpenCV reads the image data in a NumPy array. The shape() method of this ndarray object reveals image properties such as dimensions and channels.

使用 shape() 方法的命令如下:

The command to use the shape() method is as follows −

>>> img = cv.imread("OpenCV_Logo.png", 1)
>>> img.shape
(222, 180, 3)

在上述命令中:

In the above command −

  1. The first two items shape[0] and shape[1] represent width and height of the image.

  2. Shape[2] stands for a number of channels.

  3. 3 indicates that the image has Red Green Blue (RGB) channels.

类似地,size 属性返回图像大小。图像大小的命令如下:

Similarly, the size property returns the size of the image. The command for the size of an image is as follows −

>>> img.size
119880

ndarray 中的每个元素代表一个图像像素。

Each element in the ndarray represents one image pixel.

我们可以借助下面提到的命令访问和操作任何像素的值。

We can access and manipulate any pixel’s value, with the help of the command mentioned below.

>>> p=img[50,50]
>>> p
array([ 1, 1, 255], dtype=uint8)

Example

以下代码将前 100X100 个像素的颜色值更改为黑色。 imshow() 函数可以验证结果。

Following code changes the color value of the first 100X100 pixels to black. The imshow() function can verify the result.

>>> for i in range(100):
   for j in range(100):
      img[i,j]=[0,0,0]

Output

imshow

图像通道可以通过使用 split() 函数拆分为单个平面。可以通过使用 merge() 函数合并通道。

The image channels can be split in individual planes by using the split() function. The channels can be merged by using merge() function.

split() 函数返回一个多通道数组。

The split() function returns a multi-channel array.

我们可以使用以下命令拆分图像通道:

We can use the following command to split the image channels −

>>> img = cv.imread("OpenCV_Logo.png", 1)
>>> b,g,r = cv.split(img)

您现在可以对每个平面进行操作。

You can now perform manipulation on each plane.

假设我们把蓝色通道里的所有像素设为 0,代码如下 −

Suppose we set all pixels in blue channel to 0, the code will be as follows −

>>> img[:, :, 0]=0
>>> cv.imshow("image", img)

结果的图像将如下所示 −

The resultant image will be shown as below −

individual planes