Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Using OpenCV, Is it possible to crop images, like how I've done in PIL

Using PIL:

im = Image.open('0.png').convert('L')

im = im.crop((1, 1, 98, 33))

im.save('_0.png')

How is it possible in OpenCV?

I tried:

im = cv.imread('0.png', cv.CV_LOAD_IMAGE_GRAYSCALE)

(thresh, im_bw) = cv.threshold(im, 128, 255, cv.THRESH_OTSU)

im = cv.getRectSubPix(im_bw, (98, 33), (1, 1))

cv.imshow('Img', im)

cv.waitKey(0)

But it doesn't work. Can anyone suggest some ways to crop images using OpenCV?

1 Answer

0 votes
by (26.4k points)

We can use numpy slicing

import cv2

img = cv2.imread("lenna.png")

crop_img = img[y:y+h, x:x+w]

cv2.imshow("cropped", crop_img)

cv2.waitKey(0)

Want to learn more about python? Come and Join: Python course

For more information, do check out..

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 10, 2020 in Python by laddulakshana (16.4k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...