How to Crop Image Using OpenCV in Computer Vision
To crop an image in OpenCV, use array slicing on the image matrix with
image[y1:y2, x1:x2] where x1, y1 is the top-left corner and x2, y2 is the bottom-right corner of the crop area. This extracts the region of interest as a new image.Syntax
In OpenCV with Python, images are stored as arrays. Cropping uses array slicing with the syntax cropped_image = image[y1:y2, x1:x2].
image: the original image arrayy1:y2: vertical pixel range (rows)x1:x2: horizontal pixel range (columns)- The result is a new image containing only the selected rectangle.
python
cropped_image = image[y1:y2, x1:x2]
Example
This example loads an image, crops a 100x100 pixel square from coordinates (50, 50) to (150, 150), and displays both original and cropped images.
python
import cv2 # Load image from file image = cv2.imread('input.jpg') # Define crop coordinates x1, y1 = 50, 50 x2, y2 = 150, 150 # Crop the image using slicing cropped_image = image[y1:y2, x1:x2] # Show original and cropped images cv2.imshow('Original Image', image) cv2.imshow('Cropped Image', cropped_image) cv2.waitKey(0) cv2.destroyAllWindows()
Output
Two windows open: one showing the original image, the other showing the cropped 100x100 pixel area.
Common Pitfalls
- Mixing up x and y coordinates:
yis row (height),xis column (width). - Using coordinates outside image bounds causes errors or empty crops.
- Remember slicing excludes the end index pixel, so
y1:y2crops up toy2-1. - Not checking if the image loaded correctly before cropping can cause crashes.
python
import cv2 image = cv2.imread('input.jpg') # Wrong: x and y swapped # cropped = image[50:150, 50:150] # This is correct usage # Wrong: coordinates outside bounds # cropped = image[1000:1100, 1000:1100] # Likely empty or error # Right way: check image shape if image is not None: height, width = image.shape[:2] x1, y1 = 50, 50 x2, y2 = min(150, width), min(150, height) cropped = image[y1:y2, x1:x2]
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Crop image | cropped = image[y1:y2, x1:x2] | Extracts a rectangular region from the image |
| Check image shape | height, width = image.shape[:2] | Get image dimensions (height and width) |
| Show image | cv2.imshow('title', image) | Display image in a window |
| Wait for key | cv2.waitKey(0) | Waits for a key press to close window |
| Close windows | cv2.destroyAllWindows() | Closes all OpenCV windows |
Key Takeaways
Crop images in OpenCV using array slicing with image[y1:y2, x1:x2].
Always verify image loaded correctly before cropping to avoid errors.
Remember y is vertical (rows), x is horizontal (columns) in slicing.
Ensure crop coordinates are within image dimensions.
Use OpenCV functions to display images and verify cropping visually.