English 中文(简体)
OpenCV Python - Image Properties
  • 时间:2024-09-17

OpenCV Python - Image Properties


Previous Page Next Page  

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

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 −

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

    Shape[2] stands for a number of channels.

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

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


>>> img.size
119880

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

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

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

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

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


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

You can now perform manipulation on each plane.

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 −

Inspanidual Planes Advertisements