Before performing any operations, you need to load an image:
Python
C++
import cv2 as cvimport numpy as np# Read an imageimg = cv.imread('image.jpg')# Read as grayscalegray_img = cv.imread('image.jpg', cv.IMREAD_GRAYSCALE)# Display the imagecv.imshow('Image', img)cv.waitKey(0)cv.destroyAllWindows()
#include <opencv2/opencv.hpp>using namespace cv;int main() { // Read an image Mat img = imread("image.jpg"); // Read as grayscale Mat gray_img = imread("image.jpg", IMREAD_GRAYSCALE); // Display the image imshow("Image", img); waitKey(0); destroyAllWindows(); return 0;}
import cv2 as cvimg = cv.imread('image.jpg')# Crop using slicing [y1:y2, x1:x2]cropped = img[100:400, 200:500]# Crop a region of interest (ROI)x, y, w, h = 100, 50, 300, 200roi = img[y:y+h, x:x+w]cv.imshow('Cropped', cropped)cv.waitKey(0)
import cv2 as cvimport numpy as np# Load imageimg = cv.imread('input.jpg')if img is None: print('Error loading image') exit()# Resize to a standard sizeimg = cv.resize(img, (800, 600))# Apply Gaussian blur to reduce noiseblurred = cv.GaussianBlur(img, (5, 5), 0)# Crop region of interesth, w = blurred.shape[:2]roi = blurred[h//4:3*h//4, w//4:3*w//4]# Rotate the ROIcenter = (roi.shape[1]//2, roi.shape[0]//2)matrix = cv.getRotationMatrix2D(center, 15, 1.0)rotated = cv.warpAffine(roi, matrix, (roi.shape[1], roi.shape[0]))# Display resultscv.imshow('Original', img)cv.imshow('Processed', rotated)cv.waitKey(0)cv.destroyAllWindows()# Save resultcv.imwrite('output.jpg', rotated)
#include <opencv2/opencv.hpp>#include <iostream>using namespace cv;using namespace std;int main() { // Load image Mat img = imread("input.jpg"); if (img.empty()) { cout << "Error loading image" << endl; return -1; } // Resize to standard size resize(img, img, Size(800, 600)); // Apply Gaussian blur Mat blurred; GaussianBlur(img, blurred, Size(5, 5), 0); // Crop region of interest int h = blurred.rows, w = blurred.cols; Rect roi_rect(w/4, h/4, w/2, h/2); Mat roi = blurred(roi_rect); // Rotate the ROI Point2f center(roi.cols/2.0, roi.rows/2.0); Mat matrix = getRotationMatrix2D(center, 15, 1.0); Mat rotated; warpAffine(roi, rotated, matrix, roi.size()); // Display results imshow("Original", img); imshow("Processed", rotated); waitKey(0); // Save result imwrite("output.jpg", rotated); return 0;}
When working with images, always check if the image was loaded successfully before performing operations. Use if img is None: in Python or if (img.empty()) in C++.
Be careful with image data types when performing operations. OpenCV typically uses uint8 (0-255) for display, but intermediate calculations may require float32 or float64 to avoid overflow.