Let’s create a simple program to load and display an image.
1
Create your project
Create a new directory for your project:
mkdir opencv-quickstartcd opencv-quickstart
2
Write your first program
Create a file and load an image:
Python
C++
Java
Create display_image.py:
import cv2 as cvimport sys# Load an imageimg = cv.imread('image.jpg')# Check if image was loaded successfullyif img is None: sys.exit("Could not read the image.")# Display the imagecv.imshow("Display window", img)k = cv.waitKey(0)# Save if 's' key is pressedif k == ord("s"): cv.imwrite("output.png", img)
Make sure you have an image file named image.jpg in the same directory, or use cv.samples.findFile("starry_night.jpg") to use a built-in sample image.
Create display_image.cpp:
#include <opencv2/opencv.hpp>#include <iostream>int main() { // Load an image cv::Mat img = cv::imread("image.jpg"); // Check if image was loaded successfully if (img.empty()) { std::cout << "Could not read the image" << std::endl; return 1; } // Display the image cv::imshow("Display window", img); int k = cv::waitKey(0); // Save if 's' key is pressed if (k == 's') { cv::imwrite("output.png", img); } return 0;}
Create DisplayImage.java:
import org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.highgui.HighGui;import org.opencv.imgcodecs.Imgcodecs;public class DisplayImage { public static void main(String[] args) { // Load OpenCV native library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Load an image Mat img = Imgcodecs.imread("image.jpg"); // Check if image was loaded if (img.empty()) { System.out.println("Could not read the image"); return; } // Display the image HighGui.imshow("Display window", img); HighGui.waitKey(0); }}
3
Run your program
Execute your program:
Python
C++
Java
python display_image.py
Compile and run:
# Using g++g++ display_image.cpp -o display_image `pkg-config --cflags --libs opencv4`./display_image# Using CMake (recommended)# Create CMakeLists.txt firstcmake .make./display_image
import cv2 as cv# Open webcam (0 = default camera)cap = cv.VideoCapture(0)# Or open a video file# cap = cv.VideoCapture('video.mp4')while True: # Read frame ret, frame = cap.read() if not ret: break # Convert to grayscale gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # Display cv.imshow('Webcam', gray) # Break on 'q' key if cv.waitKey(1) & 0xFF == ord('q'): breakcap.release()cv.destroyAllWindows()
#include <opencv2/opencv.hpp>int main() { // Open webcam cv::VideoCapture cap(0); // Or open a video file // cv::VideoCapture cap("video.mp4"); if (!cap.isOpened()) { std::cout << "Error opening video stream" << std::endl; return -1; } cv::Mat frame, gray; while (true) { // Read frame cap >> frame; if (frame.empty()) break; // Convert to grayscale cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY); // Display cv::imshow("Webcam", gray); // Break on 'q' key if (cv::waitKey(1) == 'q') break; } cap.release(); cv::destroyAllWindows(); return 0;}