Friday, August 4, 2023

OpenCV Basics

We'll learn some basic operations supported by OpenCV, such as opening image or video files and displaying them, converting color images to grayscale, or black-white images, connecting to a webcam of a laptop and showing the videos captured by it.

1. Load Color Images

create a new Python file called ShowImage.py, or whatever you like, copy and paste the following codes, and make sure you have your image file in your PyCharm project (in my case, you can use any IDE) folder and correctly point to it.

1 import cv2

2 img = cv2.imread("../res/flower004.jpg")

3 cv2.imshow("Image", img)

4 cv2.waitKey(0)

5 cv2.destroyAllWindows()

Line 1 import cv2 tells the Python to include the cv2 (OpenCV) library. Every time when using OpenCV, must import the cv2 package. This is typically always the first statement in the code file.

Line 2 cv2.imread() is the function to load an image, the image file path is specified in the argument.

Line 3 cv2.imshow() is the function to show the image. The first argument is the title of the window that displays the image, the second argument is the image that returned from cv2. imread() function.

Line 4 Wait for a keystroke. If do not wait for a keystroke, the cv2.imshow() will display the window and go to the next immediately, the execution will complete and the window will disappear, this happens very quickly so you can hardly see the result. So cv2.waitKey() is typically added here to wait for a user to press a key.

Line 5 Destroys all windows before the execution completes.

Run the code, the loaded image is displayed, as shown in Figure below-


cv2.imread() is an OpenCV function used to load the image from a file, here is its syntax:

cv2.imread(path, flag)

Parameters

path: The path of the image to be read.

flag: Specifies how to read the image, the default value is cv2.IMREAD_COLOR.

cv2.IMREAD_COLOR: Load a color image. Any transparency of the image will be neglected. It is the default flag. You can also use 1 for this flag.

cv2.IMREAD_GRAYSCALE: Load an image in grayscale mode. You can also use 0 for this flag.

cv2.IMREAD_UNCHANGED: Load an image as such including alpha channel. You can use -1 for this flag.

Return Value 

The image that is loaded from the image file specified in the path parameter.

Now let’s load this image file in grayscale mode and display it. Just simply replace the line 2 in above codes with the following, it tells the cv2.imread() to load image in grayscale mode. img = cv2.imread("../res/flower004.jpg", cv2.IMREAD_GRAYSCALE)

Execute the code and the grayscale image is shown as Figure below-




Share:

0 comments:

Post a Comment