Opencv-python — Loading, displaying, and saving images

In this section, we will learn how to use the OpenCV library to read, display, and save images in Python. All images are a numpy. These three operations are implemented by cv2.imread(), cv2.imshow(), and cv2.imwrite(). At the end of the article, we briefly introduced the use of Matplotlib to display images. Opencv used in this article is OpencV3.2 version, the picture is as follows:

1. Read the picture

The cv2.imread() function is used to load images in OpenCV. This function has the following form:

cv2.imread(path, flags)
Copy the code

The meanings of the parameters are as follows:

  • Path: Specifies the path of the image. You can use either a relative path or an absolute path.
  • flags: Specifies how to load an image. There are three values:
    1. cv2.IMREAD_COLOR: Read a pairColor images, the transparency of the image is ignored. The default value is 1, and the actual value is 1.
    2. cv2.IMREAD_GRAYSCALETo:grayscaleRead a picture, the actual value is 0
    3. Cv2. IMREAD_UNCHANGED: Loads a color image, and transparency is not ignored.

This function does not raise an exception if the given image path is incorrect. Instead, it returns None. If the correct image path is given, it returns a numpy.ndarray object of [height, width, channel]. Channel Indicates the image channel.

import numpy as np
import cv2

img = cv2.imread("pic.jpg")
# img = cv2.imread("pic.jpg", cv2.IMREAD_COLOR)
# img = cv2.imread("pic.jpg", cv2.IMREAD_GRAYSCALE)
# img = cv2.imread("pic.jpg", cv2.IMREAD_UNCHANGED)

cv2.imshow("image", img) # Show images, explained later
cv2.waitKey(0) # wait button
Copy the code

The effect is as follows:

2. Display images

Use the cv2.imshow() function to display the image in a window that ADAPTS to the size of the image and looks like this:

cv2.imshow(winname, mat)
Copy the code

The meanings of the parameters are as follows:

1Winame: a string representing the name of the window to be created. Each window must have a unique name.2Mat: is an image matrix of type numpy. NdarrayCopy the code

During the image display process, there are usually several other functions, which are:

  • cv2.waitKey()
  • cv2.destroyAllWindows()
  • cv2.destroyWindow()
  • cv2.namedWindow()

Since our program is executed sequentially, the image would not be displayed without the cv2.waitkey () function, which is a keyboard binding function that suspends the program in milliseconds. It waits for a keyboard event for a specified time. If a keyboard event occurs within the specified time, the program continues execution. Otherwise, it must wait until the end of time to continue execution.

Cv2.destroyallwindows () destroys all Windows that have been created. If you need to destroy a specified window, use the cv2.DestroyWindow () function, which accepts a name that represents the window name.

In this case, the window created directly with cv2.imshow() is automatically sized and cannot be scaled. If we want to make the window bigger or smaller, You must use cv2.namedWindow() alone and specify the window mode to cv2.window_normal with the flag argument, which defaults to cv2.window_autosize.

Here is an example of how a window can zoom out to show a picture:

import numpy as np
import cv2

img = cv2.imshow('picture.jpg')
cv2.namedWindow('image')
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy the code

3. Save the picture

Use the cv2.imwrite() function to save the image as follows:

cv2.imwrite(filename, img)
Copy the code

The meanings of the parameters are as follows:

  • Filename: indicates the path name for saving the file
  • Img: numpy.ndarray object representing the image

4. A complete program

import numpy as np
import cv2

img = cv2.imread('messi5.jpg'.0)
cv2.imshow('image',img)
k = cv2.waitKey(0)
## k = cv2.waitKey(0) & 0xFF # 64-bit machine
if k == 27:         Exit when pressing ESC
    cv2.destroyAllWindows()
elif k == ord('s') :# Save and exit when pressing the S key
    cv2.imwrite('messigray.png',img)
    cv2.destroyAllWindows()
Copy the code

5. Use Matplotlib to display images

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('messi5.jpg'.0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # hide the x and y axes
plt.show()
Copy the code

Since OpencV loads images in BGR mode and Matplotlib displays images in RGB mode, color images loaded with OpencV will not display correctly in Matplotlib. Here is a solution

OpenCV — OpenCV color images in matplot show the solution of the problem

Since OpenCV loads images in BGR mode, while Matplotlib displays images in common RGB mode, there will be problems when color images loaded by OpenCV are displayed in Matplotlib. To solve this problem, three solutions are proposed here.

Let’s take a look at the effect of a straight line using Matplotlib to display opencV-loaded color images:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread("messi5.jpg")
cv2.imshow("BGR", img)
cv2.waitKey(0)

plt.imshow(img)
plt.title("BGR")
plt.show()
Copy the code

The first way

In this way, the cv2.split() and cv2.merge() functions are used to split the loaded images according to BGR mode, and then merge the images according to RGB mode. The code is as follows:

import cv2
import matplotlib.pyplot as plt

b, g, r = cv2.split(img)
img2 = cv2.merge([r, g, b])
plt.subplot(1.2.1)
plt.imshow(img)
plt.title("BGR")
plt.subplot(1.2.2)
plt.imshow(img2)
plt.title('RGB')
plt.show(a)Copy the code

The effect is as follows:

The second way

This method uses the reverse order of the array and transposes the last bit as follows:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread("messi5.jpg")
img2 = img[...,::- 1]

plt.subplot(1.2.1)
plt.imshow(img)
plt.title("BGR")
plt.subplot(1.2.2)
plt.imshow(img2)
plt.title('RGB')
plt.show(a)Copy the code

The effect is as follows:

The third way

Cv2.cvtcolor () : cv2.cvtcolor ()

import cv2
import matplotlib.pyplot as plt

img = cv2.imread("messi5.jpg")
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

plt.subplot(1.2.1)
plt.imshow(img)
plt.title("BGR")
plt.subplot(1.2.2)
plt.imshow(img2)
plt.title('RGB')
plt.show(a)Copy the code

The effect is as follows: