Python | CV2 rectangle()方法

时间:2020-02-23 14:42:15  来源:igfitidea点击:

在本教程中,我们将看到如何在Python中绘制矩形形状,通过使用作为CV2(计算机视觉)库存在的开放式CV在Python中。

我们可以使用 rectangle()CV2库绘制矩形的方法,在图像上的正方形。
要使用CV2库,我们需要使用CV2库使用 import statement

现在让我们看看语法和返回值 rectangle()方法,然后我们将继续执行示例。

语法

cv2.rectangle(image, starting_coordinate , ending_coordinate, color, thickness, lineType, shift)

参数

我们可以通过7个参数来resize()方法。
在7个参数中,前四个(图像,启动_coorde,ending_coord和颜色)是强制性的;休息(厚度,线型和换档)是可选的。

必要的参数是:

  • image:N维数组的输入图像。
  • starting_coordinate:启动矩形的最左坐标,以元组的形式给出。
  • ending_coordinate:结束底部的最正确坐标,其以元组的形式给出。
  • color:矩形形状的边界颜色以元组的形式给出,具有相应的BGR值。

可选参数是:

  • thickness:矩形边界的厚度(以像素为单位)。其默认值为1.
  • lineType:行类型,无论是8连接的,抗锯齿线等。默认情况下,它是8连接的。 CV.LINE_AA给出了抗锯齿线,看起来很棒。
  • shift:表示坐标中的分数位数。

返回值

它返回N维数组的输出图像,绘制矩形形状。

cv2.rectangle()方法示例

现在让我们看看Python代码: Example 1:用薄边框绘制图像上的矩形形状。

# import computer vision library(cv2) in this code
import cv2
 
# main code
if __name__ == "__main__" :
 
    # mentioning absolute path of the image
    img_path = "C:\Users\user\Desktop\flower.jpg"
 
    # reading an image in default mode
    img = cv2.imread(img_path)
 
    # show the input image on the newly created image window
    cv2.imshow('image1 window',img)
    
    # top left corner coordinate
    starting_coordinate = (10,10)
 
    # bottom right corner coordinate
    ending_coordinate = (100,150)
 
    # BGR value of black color
    color = (0,0,0)
 
    # drawing a rectangle with black colour on given image 
    new_image = cv2.rectangle(img, starting_coordinate , ending_coordinate, color)
    
    # show the output image on the newly created image window
    cv2.imshow('image2 window',new_image)

示例2:用粗体边框绘制图像上的方形形状。

# import computer vision library(cv2) in this code
import cv2
 
# main code
if __name__ == "__main__" :
 
    # mentioning absolute path of the image
    img_path = "C:\Users\user\Desktop\flower.jpg"
 
    # reading an image in default mode
    img = cv2.imread(img_path)
 
    # show the input image on the newly created image window
    cv2.imshow('image1 window',img)
    
    # top left corner coordinate
    starting_coordinate = (10,10)
 
    # bottom right corner coordinate
    ending_coordinate = (100,100)
 
    # BGR value of black color
    color = (0,0,0)
 
    # drawing a rectangle with black colour on given image 
    new_image = cv2.rectangle(img, starting_coordinate , ending_coordinate, color, 5)
    
    # show the output image on the newly created image window
    cv2.imshow('image2 window',new_image)