How to crop an image in OpenCV using Python How to crop an image in OpenCV using Python python python

How to crop an image in OpenCV using Python


It's very simple. Use numpy slicing.

import cv2img = cv2.imread("lenna.png")crop_img = img[y:y+h, x:x+w]cv2.imshow("cropped", crop_img)cv2.waitKey(0)


i had this question and found another answer here: copy region of interest

If we consider (0,0) as top left corner of image called im with left-to-right as x direction and top-to-bottom as y direction. and we have (x1,y1) as the top-left vertex and (x2,y2) as the bottom-right vertex of a rectangle region within that image, then:

roi = im[y1:y2, x1:x2]

here is a comprehensive resource on numpy array indexing and slicing which can tell you more about things like cropping a part of an image. images would be stored as a numpy array in opencv2.

:)


This code crops an image from x=0,y=0 to h=100,w=200.

import numpy as npimport cv2image = cv2.imread('download.jpg')y=0x=0h=100w=200crop = image[y:y+h, x:x+w]cv2.imshow('Image', crop)cv2.waitKey(0)