[英]Python OpenCV How to draw ractangle center of image and crop image inside rectangle?
I use Python3 OpenCV3.我使用 Python3 OpenCV3。 I want to draw ractangle center of image and crop image inside rectangle.
我想在矩形内绘制图像的 ractangle 中心和裁剪图像。 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 ?如何在矩形内绘制图像的 ractangle 中心和裁剪图像?
import cv2
import numpy as np
img = np.random.randint(0, 256, size=(100, 150, 3), dtype=np.uint8)
cv2.imshow('img', img)
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)
# 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()
You need to use numpy slicing
in order to crop the image.您需要使用
numpy slicing
来裁剪图像。
The way OpenCV
stores an image is as a numpy array
. OpenCV
存储图像的方式是一个numpy array
。 This means that you can 'crop' them as you can a numpy
array.这意味着您可以像对
numpy
数组一样“裁剪”它们。
The way to do this is with the following syntax
:这样做的方法是使用以下
syntax
:
cropped = img[top_edge : bottom_edge, left_edge : right_edge]
where top_edge
, bottom_edge
etc. are pixels
vals .其中
top_edge
、 bottom_edge
等是pixels
vals 。
The reason this works is because numpy
slicing
allows you to slice
along any axis
- each one separated by a comma.这样做的原因是因为
numpy
slicing
允许您沿任何axis
slice
- 每个axis
用逗号分隔。
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
.所以在这里,我们将
slicing
的rows
图像之间top_edge
和bottom_edge
然后逗号说,随之而来的将会影响该columns
各row
。 So for a given row
, we slice
it between left_edge
and right_edge
.因此,对于给定的
row
,我们将其slice
在left_edge
和right_edge
之间。 And that's it!就是这样!
Hope this is useful!希望这是有用的! :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.