Python OpenCV How to draw ractangle center of image and crop image inside rectangle?
Solution 1
create an image
import cv2
import numpy as np
img = np.random.randint(0, 256, size=(100, 150, 3), dtype=np.uint8)
cv2.imshow('img', img)
draw a rectangle
height, width, channels = img.shape
upper_left = (width // 4, height // 4)
bottom_right = (width * 3 // 4, height * 3 // 4)
# draw in the image
cv2.rectangle(img, upper_left, bottom_right, (0, 255, 0), thickness=1)
cv2.imshow('draw_img', img)
fill values by indexing
# indexing array
rect_img = img[upper_left[1]: bottom_right[1] + 1, upper_left[0]: bottom_right[0] + 1]
rect_img[:] = (255, 0, 0) # modify value
cv2.imshow('index_img', img)
cv2.waitKey()
Solution 2
You need to use numpy slicing
in order to crop the image.
The way OpenCV
stores an image is as a numpy array
. This means that you can 'crop' them as you can a numpy
array.
The way to do this is with the following syntax
:
cropped = img[top_edge : bottom_edge, left_edge : right_edge]
where top_edge
, bottom_edge
etc. are pixels
vals.
The reason this works is because numpy
slicing
allows you to slice
along any axis
- each one separated by a comma.
So here, we are slicing
the rows
of the image to between top_edge
and bottom_edge
and then the comma says that what comes next is going to effect the columns
in each row
. So for a given row
, we slice
it between left_edge
and right_edge
. And that's it!
Hope this is useful! :)
user902633
Updated on July 23, 2022Comments
-
user902633 almost 2 years
I use Python3 OpenCV3. I want to draw ractangle center of image and crop image inside rectangle. I try to run this code but rectangle not show at the center of image.
width, height, channels = img.shape cv2.rectangle(img,(0,0),(int(width/2), int(height/2)), (0,255,0) , 2)
How to draw ractangle center of image and crop image inside rectangle ?