Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are 2 ways to do this. Draw manually:

#!/usr/bin/python3.7
#Raspberry pi 3/4, OpenCV 4.1.2
#Date: 5th December, 2019

import cv2

img = cv2.imread('x.jpg')
c, r, w, h =  100, 100, 640,480
roi = img[r:r + h, c:c + w ]
cv2.imshow('ROI', roi)
cv2.waitKey(0)

And API:

#!/usr/bin/python3.7
#Raspberry pi 3/4, OpenCV 4.1.2
#Date: 5th December, 2019

import cv2 as cv

im = cv.imread("lena.jpg")

showCrosshair = False
fromCenter = False 
# Select ROI
r = cv.selectROI(im, fromCenter, showCrosshair)

# Crop image
imCrop = im[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]

# Display cropped image
cv.imshow("Image", imCrop)
cv.waitKey(0)
cv.imwrite('lena_roi.jpg', imCrop)

Select a ROI and then press SPACE or ENTER button! Cancel the selection process by pressing c button!

There are 2 ways to do this. Draw manually:

#!/usr/bin/python3.7
#Raspberry pi 3/4, OpenCV 4.1.2
#Date: 5th December, 2019

import cv2

img = cv2.imread('x.jpg')
c, r, w, h =  100, 100, 640,480
roi = img[r:r + h, c:c + w ]
cv2.imshow('ROI', roi)
cv2.waitKey(0)

And API:

#!/usr/bin/python3.7
#Raspberry pi 3/4, OpenCV 4.1.2
#Date: 5th December, 2019

import cv2 as cv

im = cv.imread("lena.jpg")

showCrosshair = False
fromCenter = False 
# Select ROI
r = cv.selectROI(im, fromCenter, showCrosshair)

# Crop image
imCrop = im[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]

# Display cropped image
cv.imshow("Image", imCrop)
cv.waitKey(0)
cv.imwrite('lena_roi.jpg', imCrop)

  1. Select a ROI and then press SPACE or or ENTER button! button!
  2. Cancel the selection process by
    pressing c button!