Loading images – OpenCV 3.4 with python 3 Tutorial 1

Show images

Load and show images with Opencv is a really simple operation.
On Line 1 we import the opencv library.

On Line 3 we load the image into a variable. You can put just the title of the image and the format (example .jpg) if the image is in the same folder as the python file, otherwise you need to insert the full path, if the image is on another folder.
For example if you have it on the desktop, it would look something like this cv2.imread(“C:\Users\myusername\Desktop\red_panda.jpg”)

On Line 3 we convert it into a black and white image, or better to say gray scale image as there will be different gradients of black and of white.

Finally on Line 6 and Line 7 we show both images, the one with original color and the one in gray scale format.

On Line 8 we have the function that keeps the images open. cv2.waitKey(0) is literally waiting that you press a key. If you press for example “ESC”, it will close all the windows.

On Line 9 it destroy all the windows. It won’t make any difference in this simple code, as the windows will be destroied anyway because the code will finish its execution, but for example if you have a bigger program and later there are some other lines of code running, then the windows might still be open.
So it’s always a good practice to put that line at the end.

[python]import cv2

image = cv2.imread("red_panda.jpg")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cv2.imshow("Gray panda", gray_image)
cv2.imshow("Red panda", image)
cv2.waitKey(0)
cv2.destroyAllWindows()[/python]

Save images

Save images is also a really simple operation.

After we load the image, on Line 6 we are going to save it.
You need to insert two parameters. The first one is the title, followed by the format of the image “gray_panda.jpg” if you want to save it in jpg format or “gray_panda.png” if you want png format.
Second parameter is the image that you want to save, in this case we’re saving the gray image.
[python]import cv2

image = cv2.imread("red_panda.jpg")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cv2.imwrite("gray_panda.jpg", gray_image)[/python]
Files:
1) red_panda.jpg