用Python的OpenCV绘制矩形形状并提取对象

用Python的OpenCV绘制矩形形状并提取对象

OpenCV是一个开源的Python计算机视觉库。它提供了许多函数来执行各种图像和视频处理操作。该库使用numpy模块将所有视频帧和图像表示为ndarray类型。我们需要安装numpy库,并确保它也安装在我们的Python解释器中。

在本文中,我们将看到使用Python的OpenCV绘制矩形形状和提取对象的不同方法。

绘制矩形

要在图像上绘制矩形形状,Python的OpenCV模块提供了一个名为cv2.rectangle()的方法。该方法将在图像上绘制矩形形状。以下是语法-

cv.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]] )

参数

  • img:要绘制矩形的源图像。
  • pt1:一个包含矩形一个顶点(矩形左上角)的x和y坐标的元组。
  • pt2:一个包含矩形另一个顶点(相对于上一个顶点的矩形右下角)的x和y坐标的元组。
  • color:指定矩形的颜色。
  • thickness:可选参数。指定矩形线的粗细。默认为1。
x1,y1----------|
|          | 
|          |
| ------------x2,y2

因此,pt1和pt2的坐标将分别为(x1,y1)和(x2,y2)。

使用预定义的尺寸

在这种方法中,我们将使用预定义的坐标在图像上绘制矩形形状。这意味着我们将手动定义pt1、pt2的值。

示例

在这个示例中,我们将使用图像坐标来绘制和提取矩形形状中的对象。

import cv2
import numpy as np

# Load the image
img = cv2.imread("Images/Tajmahal.jpg")

# Define the dimensions and position of the rectangle using two points
top_left = (80, 80)
bottom_right = (500, 300)

# defining the colour and thickness of the rectangle
thickness = 2 
color = (0, 255, 0) # Green color
shape = cv2.rectangle(img, top_left, bottom_right, color, thickness)

# Extracting objects from the rectangular area
rect_area = img[top_left[0]:bottom_right[1], top_left[1]:bottom_right[0]]

# Display the image with the drawn rectangle
cv2.imshow("Image with Rectangle", img)

# Display the extracted rectangular area
cv2.imshow("Rectangular Area", rect_area)

cv2.waitKey(0)
cv2.destroyAllWindows()

输出

用Python的OpenCV绘制矩形形状并提取对象

裁剪的图像

使用鼠标事件标志

为了在图像上绘制矩形形状,我们将使用以下鼠标事件:

  • cv2.EVENT_RBUTTONDOWN:表示右键被按下。

  • cv2.EVENT_LBUTTONUP:表示左键被释放。

此外,我们将使用setMouseCallback()函数为指定的窗口设置鼠标事件处理程序。

setMouseCallback()函数

该函数用于指定在特定窗口中调用哪个函数。换句话说,该函数为指定的窗口创建一个鼠标事件处理程序。

语法

cv2.setMouseCallback(winname, onMouse, userdata)

参数

  • Winname:特定窗口的名称。
  • OnMouse:鼠标事件的回调函数。
  • Userdata:传递给回调函数的可选参数。

可以使用命令行界面执行此方法。因此,我们将使用argparse模块,因为它提供了一个方便的接口来处理命令行参数。

首先,我们将设置一个鼠标回调函数来读取用户绘制的矩形坐标。通过使用鼠标单击事件,我们将识别x和y坐标,然后使用cv2.rectangle()函数绘制矩形形状。

注意-要执行此代码,我们需要将程序文件保存在同一位置并在命令提示符中运行以下命令。

Python program_file_name.py --image source_image_name.jpg

示例

让我们举一个示例来绘制矩形形状以提取对象。

import cv2
import argparse

point = []
crop = False

def shape_selection(event, x, y, flags, param):
   # grab references to the global variables
   global point, crop

   # Record the starting(x, y) coordinates when the left mouse button was clicked
   if event == cv2.EVENT_LBUTTONDOWN:
      point = [(x, y)]

   # check to see if the left mouse button was released
   elif event == cv2.EVENT_LBUTTONUP:
      # record the ending (x, y) coordinates 
      point.append((x, y))

      # draw a rectangle
      cv2.rectangle(image, point[0], point[1], (0, 255, 0), 2)
      cv2.imshow("image", image)

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help ="Images/Dog.jpg")
args = vars(ap.parse_args())

# load the image
image = cv2.imread(args["image"])
clone = image.copy()
cv2.namedWindow("image")
# setting the mouse callback function
cv2.setMouseCallback("image", shape_selection)

# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF

    # press 'r' to reset window 
    if key == ord("r"):
        image = clone.copy()

    # if the 'c' key is pressed, break from the loop
    elif key == ord("c"):
        break

if len(point) == 2:
    crop_img = clone[point[0][1]:point[1][1], point[0][0]:point[1][0]]
    cv2.imshow("crop_img", crop_img)
    cv2.waitKey(0)

    # close all open windows
cv2.destroyAllWindows()

打开命令提示符,使用以下命令执行上述程序 –

python test.py --image image5.jpg

这将生成一个窗口,显示输入图像,你可以在上面选择所需的对象,如下所示 –

用Python的OpenCV绘制矩形形状并提取对象

请注意−在选择所需的图像区域后,按键盘上的C键进行裁剪。

用Python的OpenCV绘制矩形形状并提取对象

我们成功地绘制了矩形形状并从图像中提取出了所选的对象。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程