In this python opencv example code, we will show you how to crop an image in python opencv. It is very easy.
Step 1. import python opencv library
Step 2: open an image using python opencv
We will use cv2.imread() to open an image in opencv.
img = cv2.imread("bird2.jpg")
Step 3: crop the image by an area
img is an numpy ndarray, we can select some data to save.
x = 100 y = 100 h = 300 w = 300 cropped_image = img[y:y+h,x:x+w]
Step 4: show and save cropped image
cv2.imshow("Cropped Image",cropped_image) cv2.imshow("OriginalImage",img) cv2.imwrite("Cropped Image.jpg", cropped_image) cv2.waitKey(0)
Finally, we will see an image below: