简体   繁体   English

Python OpenCV 如何在矩形内绘制图像的 ractangle 中心和裁剪图像?

[英]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 中心和裁剪图像?

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()

在此处输入图片说明

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_edgebottom_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 .所以在这里,我们将slicingrows图像之间top_edgebottom_edge然后逗号说,随之而来的将会影响该columnsrow So for a given row , we slice it between left_edge and right_edge .因此,对于给定的row ,我们将其sliceleft_edgeright_edge之间。 And that's it!就是这样!

Hope this is useful!希望这是有用的! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM