Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

OpenCV Getting Started Examples

OpenCV Getting Started Examples

Next, let's look at a simple OpenCV example. We will implement the following functions:

  1. Read an image.

  2. Display the image.

  3. Save the image.

  4. Add simple user interaction.

You can use the following image as an example:

The following code is saved in the display_image.py file:

Example (Python)

Import the OpenCV library

import

cv2

1. Read the image

Replace with the actual image path; here it is "bird.jpg" in the current directory

image_path

=

"./bird.jpg"

image

=

cv2.

imread

(

image_path

)

Check whether the image was read successfully

if

image

is

None

:

   

print

(

"Error: unable to load image, please check whether the path is correct."

)

    exit

(

)

2. Display the image

Create a window named "Display Image" and display the image in it

cv2.

imshow

(

"Display Image"

,

image

)

3. Wait for a key press

The parameter 0 means wait indefinitely until the user presses any key

key

=

cv2.

waitKey

(

0

)

4. Perform actions based on the key pressed

if

key

==

ord

(

's'

)

:  

If the 's' key is pressed

   

Save the image

    output_path

=

"saved_image.jpg"

    cv2.

imwrite

(

output_path

,

image

)

   

print

(

f

"Image saved as {output_path}"

)

else

:  

If any other key is pressed

   

print

(

"Image not saved."

)

5. Close all windows

cv2.

destroyAllWindows

(

)

Execute the following command:



python display_image.py

The pop-up window is shown below:

In the displayed image window, press the s key to save the image, or press any other key to exit.

The C++ code for the above example is as follows:

Example (C++)

#include

#include

using

namespace

cv

;

using

namespace

std

;

int

main

(

)

{

   

// 1. Read the image

   

// Replace with the actual image path; here it is "bird.jpg" in the current directory

    string image_path

=

"./bird.jpg"

;

    Mat image

=

imread

(

image_path

)

;

   

// Check whether the image was read successfully

   

if

(

image.

empty

(

)

)

{

       

cout

<<

"Error: unable to load image, please check whether the path is correct."

<<

endl

;

       

return

1

;

   

}

   

// 2. Display the image

   

// Create a window named "Display Image" and display the image in it

    namedWindow

(

"Display Image"

, WINDOW_AUTOSIZE

)

;

    imshow

(

"Display Image"

, image

)

;

   

// 3. Wait for a key press

   

// The parameter 0 means wait indefinitely until the user presses any key

   

int

key

=

waitKey

(

0

)

;

   

// 4. Perform actions based on the key pressed

   

if

(

key

==

's'

)

{

 

// If the 's' key is pressed

       

// save the image

        string output_path

=

"saved_image.jpg"

;

        imwrite

(

output_path, image

)

;

       

cout

<<

"Image saved as "

<<

output_path

<<

endl

;

   

}

else

{

 

// If any other key is pressed

       

cout

<<

"Image not saved."

<<

endl

;

   

}

   

// 5. Close all windows

    destroyAllWindows

(

)

;

   

return

0

;

}

Extended Exercises

Next, we can try making some modifications to the code.

**1. Change the window name:** Change "Display Image" to another name, such as "My Image".

cv2.imshow("My Image", image)

**2. Save in a different format:** Change "saved_image.jpg" to "saved_image.png" and observe the saved result.

# 4. 根据用户按键执行操作

if key == ord('s'):  # 如果按下 's' 键

    # Save image

    output_path = "saved_image.png"

    cv2.imwrite(output_path, image)

    print(f"图像已保存为 {output_path}")

**3. Add more interactions:** For example, press the 'q' key to exit the program directly.

if key == ord('s'):  # 如果按下 's' 键

    # Save image

    output_path = "saved_image.jpg"

    cv2.imwrite(output_path, image)

    print(f"图像已保存为 {output_path}")

elif key == ord('q'):  # 如果按下 'q' 键

    print("程序已退出。")

else:  # 如果按下其他键

    print("图像未保存,程序已退出。")