1. Displaying an Image Using OpenCV
OpenCV is widely used for image processing tasks. In this article, we will demonstrate how to read, display, and print an image matrix using OpenCV in both Python and C++.
Python Example
Below is a simple Python script that loads and displays an image:
import cv2 as cv
# Read the image
img = cv.imread("lena.jpg", 1) # 1 indicates loading a color image
# Display the image
cv.imshow('image', img)
# Print the image matrix
print(img)
# Wait for 10 seconds before closing
cv.waitKey(10000)
cv.destroyAllWindows()
Explanation
- cv.imread(“lena.jpg”, 1) loads the image in color mode (1 indicates a color image, 0 for grayscale).
- cv.imshow(‘image’, img) opens a window displaying the image.
- print(img) outputs the image matrix to the console.
- cv.waitKey(10000) waits for 10 seconds before proceeding.
- cv.destroyAllWindows() closes all OpenCV windows.
What is Scope resolution (Optional to read)
The ::
operator in cv::Mat
and cv::imread
is called the scope resolution operator in C++. It is used to specify which namespace or class a particular function or variable belongs to.
Explanation:
cv::Mat
:cv
is the namespace used in OpenCV.Mat
is a class inside thecv
namespace that represents an image (matrix).cv::Mat
means thatMat
is being used from thecv
namespace.
cv::imread("lena.jpg", 1)
:imread
is a function in OpenCV that loads an image from a file.cv::imread
means we are using theimread
function from thecv
namespace.
Why Use ::
?
Namespaces help avoid name conflicts. For example, if you have another function named imread()
in your code or a different library, cv::imread()
ensures that you are specifically calling OpenCV’s imread()
function.
Alternative:
Instead of writing cv::
every time, you can add:
using namespace cv;
Then you can simply write:
Mat img = imread("lena.jpg", 1);
How to define the namespace? (Optional read )
Here, we define a custom namespace called MyNamespace
that contains a function greet()
. When you call greet()
, you use the scope resolution operator (::
) to tell the compiler that you are referring to the function defined inside MyNamespace
.
#include <iostream>
namespace MyNamespace {
// Define a function within the namespace.
void greet() {
std::cout << "Hello from MyNamespace!" << std::endl;
}
}
int main() {
// Use the scope resolution operator to call greet() from MyNamespace.
MyNamespace::greet();
return 0;
}
Explanation:
In main()
, MyNamespace::greet()
calls the function from that namespace, avoiding any potential naming conflicts.
namespace MyNamespace { ... }
creates a scope called MyNamespace
.
Inside the namespace, greet()
is defined.
C++ Version
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
// Read the image in color mode
cv::Mat img = cv::imread("lena.jpg", 1);
if (img.empty()) {
std::cerr << "Error: Could not load image!" << std::endl;
return -1;
}
// Display the image
cv::imshow("image", img);
// Print the image matrix
std::cout << img << std::endl;
// Wait for 10 seconds before closing
cv::waitKey(10000);
cv::destroyAllWindows();
return 0;
}
Explanation
- cv::imread(“lena.jpg”, 1) loads the image in color mode.
- cv::imshow(“image”, img) displays the image.
- std::cout << img << std::endl; prints the image matrix.
- cv::waitKey(10000); waits for 10 seconds before closing.
- cv::destroyAllWindows(); closes all OpenCV windows.
This simple example illustrates how to load and display images using OpenCV in both Python and C++. You can further enhance it by adding image processing techniques like filtering or edge detection!
2. Working with Images in OpenCV
OpenCV is a powerful computer vision library that allows developers to process images efficiently. In this article, we will go through a simple example of loading, displaying, and saving an image using OpenCV in Python and C++.
Python Example
The following Python script demonstrates basic image handling using OpenCV:
import cv2 as cv
# Load an image
img = cv.imread("lena.jpg")
# Display the image
cv.imshow('image', img)
# Print the image matrix
print(img)
# Wait for 2 seconds
cv.waitKey(2000)
# Save the image
cv.imwrite('lena_black_and_white.png', img)
# Close all OpenCV windows
cv.destroyAllWindows()
Explanation
- cv.imread(“lena.jpg”) loads an image from the specified path.
- cv.imshow(‘image’, img) displays the loaded image.
- print(img) prints the image as a matrix (useful for debugging).
- cv.waitKey(2000) waits for 2000 milliseconds (2 seconds) before proceeding.
- cv.imwrite(‘lena_black_and_white.png’, img) saves the image with a new filename.
- cv.destroyAllWindows() closes any OpenCV windows.
C++ Version
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
// Load an image
cv::Mat img = cv::imread("lena.jpg");
if (img.empty()) {
std::cerr << "Error: Could not load image!" << std::endl;
return -1;
}
// Display the image
cv::imshow("image", img);
// Print image matrix
std::cout << img << std::endl;
// Wait for 2 seconds
cv::waitKey(2000);
// Save the image
cv::imwrite("lena_black_and_white.png", img);
// Close OpenCV windows
cv::destroyAllWindows();
return 0;
}
Explanation
- cv::imread(“lena.jpg”) loads an image.
- cv::imshow(“image”, img) displays the image.
- std::cout << img << std::endl; prints the image matrix.
- cv::waitKey(2000); waits for 2 seconds before proceeding.
- cv::imwrite(“lena_black_and_white.png”, img); saves the image.
- cv::destroyAllWindows(); closes any OpenCV windows.
This example provides a simple way to handle images using OpenCV in both Python and C++. You can extend it further by applying filters, transformations, or other image processing techniques!
3. Handling Keyboard Events in OpenCV
OpenCV provides flexible ways to interact with images. This article demonstrates how to load, display, and handle keyboard events while working with images in both Python and C++.
Python Example
Below is a Python script that loads an image and waits for user input to close or save it:
import cv2 as cv
# Read the image in grayscale mode
img = cv.imread('lena.jpg', 0)
# Display the image
cv.imshow('image', img)
# Wait indefinitely for a key press
k = cv.waitKey(0)
# If 'ESC' key (27) is pressed, close the window
if k == 27:
cv.destroyAllWindows()
# If 'w' key is pressed, save the image and close the window
elif k == ord('w'):
cv.imwrite('lena_black&white.png', img)
cv.destroyAllWindows()
Explanation
- cv.imread(“lena.jpg”, 0) loads the image in grayscale mode.
- cv.imshow(‘image’, img) opens a window displaying the image.
- cv.waitKey(0) waits indefinitely for a key press.
- If the ESC key (27) is pressed, cv.destroyAllWindows() closes all OpenCV windows.
- If the ‘w’ key is pressed, the image is saved as ‘lena_black&white.png’ and the windows close.
C++ Version
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
// Read the image in grayscale mode
cv::Mat img = cv::imread("lena.jpg", 0);
if (img.empty()) {
std::cerr << "Error: Could not load image!" << std::endl;
return -1;
}
// Display the image
cv::imshow("image", img);
// Wait indefinitely for a key press
int k = cv::waitKey(0);
// If 'ESC' key is pressed, close the window
if (k == 27) {
cv::destroyAllWindows();
}
// If 'w' key is pressed, save the image and close the window
else if (k == 'w') {
cv::imwrite("lena_black&white.png", img);
cv::destroyAllWindows();
}
return 0;
}
Explanation
- cv::imread(“lena.jpg”, 0) loads the image in grayscale mode.
- cv::imshow(“image”, img) displays the image.
- cv::waitKey(0); waits indefinitely for a key press.
- If ESC (27) is pressed, the window closes.
- If ‘w’ is pressed, the image is saved and the window closes.
This example demonstrates how to handle keyboard interactions in OpenCV, making it easier to implement interactive image processing applications.
4. Working with Video in OpenCV
OpenCV provides powerful tools for working with video streams. This article demonstrates how to capture and display video using OpenCV in both Python and C++.
Python Example
Below is a Python script that captures video from a webcam, converts it to grayscale, and displays it in real-time:
import cv2 as cv
# Capture video from the default camera
vid = cv.VideoCapture(0)
while True:
sig, frame = vid.read()
# Convert the frame to grayscale
gray_img = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the grayscale video frame
cv.imshow('frame', gray_img)
# Break the loop when 'q' is pressed
if cv.waitKey(1) == ord('q'):
break
# Release the video capture object and close windows
vid.release()
cv.destroyAllWindows()
Explanation
- cv.VideoCapture(0) initializes the webcam (0 refers to the default camera).
- vid.read() captures each frame from the video stream.
- cv.cvtColor(frame, cv.COLOR_BGR2GRAY) converts the frame to grayscale.
- cv.imshow(‘frame’, gray_img) displays the processed video frame.
- cv.waitKey(1) == ord(‘q’) waits for the ‘q’ key to be pressed to exit the loop.
- vid.release() releases the webcam resource.
- cv.destroyAllWindows() closes all OpenCV windows.
C++ Version
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
// Capture video from the default camera
cv::VideoCapture vid(0);
if (!vid.isOpened()) {
std::cerr << "Error: Could not open camera!" << std::endl;
return -1;
}
cv::Mat frame, gray_img;
while (true) {
vid >> frame;
if (frame.empty()) break;
// Convert frame to grayscale
cv::cvtColor(frame, gray_img, cv::COLOR_BGR2GRAY);
// Display the grayscale video frame
cv::imshow("frame", gray_img);
// Break the loop when 'q' is pressed
if (cv::waitKey(1) == 'q') {
break;
}
}
// Release the video capture object and close windows
vid.release();
cv::destroyAllWindows();
return 0;
}
Explanation
- cv::VideoCapture vid(0) initializes the webcam.
- vid >> frame; captures each frame.
- cv::cvtColor(frame, gray_img, cv::COLOR_BGR2GRAY); converts the frame to grayscale.
- cv::imshow(“frame”, gray_img); displays the processed video.
- cv::waitKey(1) == ‘q’ waits for the ‘q’ key to be pressed to exit the loop.
- vid.release(); releases the webcam resource.
- cv::destroyAllWindows(); closes all OpenCV windows.
This example demonstrates real-time video processing using OpenCV in both Python and C++.
5. Drawing Shapes on Images using OpenCV
OpenCV provides powerful tools to draw shapes on images. This article demonstrates how to draw lines, arrows, rectangles, circles, and text on images using OpenCV in Python and C++.
Python Example
Below is a Python script that loads an image and draws an arrowed line on it:
import numpy as np
import cv2 as cv
# Read the image
img = cv.imread('lena.jpg')
# Draw an arrowed line from (0,0) to (255,255) in green with thickness 5
img = cv.arrowedLine(img, (0, 0), (255, 255), (0, 255, 0), 5)
# Display the image
cv.imshow('image', img)
cv.waitKey(0)
cv.destroyAllWindows()
Explanation
- cv.imread(‘lena.jpg’) loads the image.
- cv.arrowedLine(img, (0, 0), (255, 255), (0, 255, 0), 5) draws an arrowed line.
- cv.imshow(‘image’, img) displays the image.
- cv.waitKey(0) waits for a key press before closing the window.
- cv.destroyAllWindows() closes all OpenCV windows.
Additional Examples
Drawing a Simple Line
img = cv.line(img, (50, 50), (200, 50), (255, 0, 0), 3)
This draws a blue line from (50,50) to (200,50) with thickness 3.
Drawing a Rectangle
img = cv.rectangle(img, (100, 100), (300, 300), (0, 0, 255), 4)
This draws a red rectangle from (100,100) to (300,300) with thickness 4.
Drawing a Circle
img = cv.circle(img, (250, 250), 50, (255, 255, 0), -1)
This draws a filled yellow circle at (250,250) with radius 50.
Drawing Text
font = cv.FONT_HERSHEY_SIMPLEX
img = cv.putText(img, 'OpenCV!', (50, 400), font, 1, (0, 255, 255), 2, cv.LINE_AA)
This writes ‘OpenCV!’ at position (50,400) with yellow color.
C++ Version
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
// Read the image
cv::Mat img = cv::imread("lena.jpg");
if (img.empty()) {
std::cerr << "Error: Could not load image!" << std::endl;
return -1;
}
// Draw an arrowed line from (0,0) to (255,255) in green with thickness 5
cv::arrowedLine(img, cv::Point(0, 0), cv::Point(255, 255), cv::Scalar(0, 255, 0), 5);
// Display the image
cv::imshow("image", img);
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}
Explanation
- cv::imread(“lena.jpg”) loads the image into a cv::Mat object.
- if (img.empty()) checks if the image was loaded successfully.
- cv::arrowedLine(img, cv::Point(0, 0), cv::Point(255, 255), cv::Scalar(0, 255, 0), 5) draws an arrowed line.
- cv::imshow(“image”, img) displays the image in a window.
- cv::waitKey(0) waits for a key press before closing the window.
- cv::destroyAllWindows() closes all OpenCV windows.
Additional C++ Examples
Drawing a Line
cv::line(img, cv::Point(50, 50), cv::Point(200, 50), cv::Scalar(255, 0, 0), 3);
Drawing a Rectangle
cv::rectangle(img, cv::Point(100, 100), cv::Point(300, 300), cv::Scalar(0, 0, 255), 4);
Drawing a Circle
cv::circle(img, cv::Point(250, 250), 50, cv::Scalar(255, 255, 0), -1);
Drawing Text
cv::putText(img, “OpenCV!”, cv::Point(50, 400), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 255, 255), 2, cv::LINE_AA);
This guide demonstrates how to use OpenCV to draw various shapes on images, making it useful for annotations and visual representations.
THANK YOU