欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OpenCV 3 drawing rectangle - 绘制 rectangle

程序员文章站 2022-05-21 09:34:33
...

OpenCV 3 drawing rectangle - 绘制 rectangle

OpenCV documentation index - OpenCV 文档索引
https://www.docs.opencv.org/

master (4.x)
https://www.docs.opencv.org/master/

3.4 (3.4.x)
https://www.docs.opencv.org/3.4/

2.4 (2.4.x)
https://www.docs.opencv.org/2.4/

1. 3.4 (3.4.x) -> Modules -> Image Processing -> Drawing Functions -> rectangle()

1.1 Function Documentation - rectangle()

void cv::rectangle (InputOutputArray img,
Point pt1,
Point pt2,
const Scalar & color,
int thickness = 1,
int lineType = LINE_8,
int shift = 0 
)		

Python

img = cv.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])
#include <opencv2/imgproc.hpp>

Draws a simple, thick, or filled up-right rectangle.
绘制一个简单的,粗的或实心的直角矩形。

The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners are pt1 and pt2.
函数 cv::rectangle 绘制一个矩形轮廓或一个填充的矩形,其两个相对角为 pt1 和 pt2。

Parameters
img - Image.
pt1 - Vertex of the rectangle.
pt2 - Vertex of the rectangle opposite to pt1 .
color - Rectangle color or brightness (grayscale image).
thickness - Thickness of lines that make up the rectangle. Negative values, like FILLED, mean that the function has to draw a filled rectangle.
lineType - Type of the line. See LineTypes
shift - Number of fractional bits in the point coordinates.

vertex [ˈvɜːteks]:n. 顶点,头顶,天顶
opposite [ˈɒpəzɪt; ˈɒpəsɪt]:adj. 相反的,对面的,对立的 n. 对立面,反义词 prep. 在...的对面 adv. 在对面
void cv::rectangle	(Mat & img,
Rect rec,
const Scalar & color,
int thickness = 1,
int lineType = LINE_8,
int shift = 0 
)	

Python

img = cv.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])
#include <opencv2/imgproc.hpp>

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
这是一个重载的成员函数,为方便起见而提供。它与上面的函数的不同之处仅在于它接受什么参数。

use rec parameter as alternative specification of the drawn rectangle: r.tl() and r.br()-Point(1,1) are opposite corners

def rectangle(img, pt1, pt2, color, thickness=None, lineType=None, shift=None): # real signature unknown; restored from __doc__
    """
    rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> img
    .   @brief Draws a simple, thick, or filled up-right rectangle.
    .   
    .   The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners
    .   are pt1 and pt2.
    .   
    .   @param img Image.
    .   @param pt1 Vertex of the rectangle.
    .   @param pt2 Vertex of the rectangle opposite to pt1 .
    .   @param color Rectangle color or brightness (grayscale image).
    .   @param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED,
    .   mean that the function has to draw a filled rectangle.
    .   @param lineType Type of the line. See #LineTypes
    .   @param shift Number of fractional bits in the point coordinates.
    """
    pass

2. 2.4.13 (2.4.x) -> core. The Core Functionality -> Drawing Functions -> rectangle()

https://docs.opencv.org/2.4/index.html

2.1 Function Documentation - rectangle()

Draws a simple, thick, or filled up-right rectangle.

C++: 
void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)

C++: 
void rectangle(Mat& img, Rect rec, const Scalar& color, int thickness=1, int lineType=8, int shift=0 )

Python: 
cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) → None

C: 
void cvRectangle(CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int line_type=8, int shift=0 )¶

Python: 
cv.Rectangle(img, pt1, pt2, color, thickness=1, lineType=8, shift=0) → None

Parameters
img - Image.
pt1 - Vertex of the rectangle.
pt2 - Vertex of the rectangle opposite to pt1 .
color - Rectangle color or brightness (grayscale image).
thickness - Thickness of lines that make up the rectangle. Negative values, like FILLED, mean that the function has to draw a filled rectangle.
lineType - Type of the line. See LineTypes
shift - Number of fractional bits in the point coordinates.

The function rectangle draws a rectangle outline or a filled rectangle whose two opposite corners are pt1 and pt2, or r.tl() and r.br()-Point(1,1).

3. rectangle

cv2.rectangle(image, start_point, end_point, color, thickness)

image: It is the image on which rectangle is to be drawn.
start_point: It is the starting coordinates of rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
end_point: It is the ending coordinates of rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
color: It is the color of border line of rectangle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.
thickness: It is the thickness of the rectangle border line in px. Thickness of -1 px will fill the rectangle shape by the specified color.

3.1 Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Yongqiang Cheng

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

import os
import sys

sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
current_directory = os.path.dirname(os.path.abspath(__file__))

import numpy as np
# import tensorflow as tf
import cv2
# import time


def inference(image_file, current_directory):
    img = cv2.imread(image_file, cv2.IMREAD_COLOR)

    # get dimensions of image
    dimensions = img.shape

    # height, width, number of channels in image
    height = img.shape[0]
    width = img.shape[1]
    channels = img.shape[2]

    print('Image Dimension    : ', dimensions)
    print('Image Height       : ', height)
    print('Image Width        : ', width)
    print('Number of Channels : ', channels)

    # Start coordinate, here (400, 200)
    # represents the top left corner of rectangle
    start_point = (400, 200)

    # Ending coordinate, here (800, 600)
    # represents the bottom right corner of rectangle
    end_point = (800, 600)

    # Blue color in BGR
    color = (255, 0, 0)

    # Line thickness of 6 px
    thickness = 6

    # Using cv2.rectangle() method
    # Draw a rectangle with blue line borders of thickness of 6 px
    img = cv2.rectangle(img, start_point, end_point, color, thickness)

    tmp_directory = current_directory + "/tmp"
    if not os.path.exists(tmp_directory):
        os.makedirs(tmp_directory)

    cv2.namedWindow("Press ESC on keyboard to exit.", cv2.WINDOW_NORMAL)

    # Display the resulting frame
    cv2.imshow("Press ESC on keyboard to exit.", img)

    k = cv2.waitKey(0)
    if k == 27:  # wait for ESC key to exit
        pass
    elif k == ord('s'):  # wait for 's' key to save and exit
        image_name = "%s/%s.jpg" % (tmp_directory, "source_image")
        cv2.imwrite(image_name, img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])

    # When everything done, release the capture
    cv2.destroyAllWindows()


if __name__ == '__main__':
    image_file = "./tmp/000505.jpg"

    os.environ["CUDA_VISIBLE_DEVICES"] = '0'
    print("os.environ['CUDA_VISIBLE_DEVICES']:", os.environ['CUDA_VISIBLE_DEVICES'])

    inference(image_file, current_directory)

OpenCV 3 drawing rectangle - 绘制 rectangle

/usr/bin/python2.7 /home/strong/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow/yongqiang.py --gpu=0
os.environ['CUDA_VISIBLE_DEVICES']: 0
Image Dimension    :  (1080, 1920, 3)
Image Height       :  1080
Image Width        :  1920
Number of Channels :  3

Process finished with exit code 0

3.2 Example

Using thickness of -1 px to fill the rectangle by blue color.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Yongqiang Cheng

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

import os
import sys

sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
current_directory = os.path.dirname(os.path.abspath(__file__))

import numpy as np
# import tensorflow as tf
import cv2


# import time


def inference(image_file, current_directory):
    img = cv2.imread(image_file, cv2.IMREAD_COLOR)

    # get dimensions of image
    dimensions = img.shape

    # height, width, number of channels in image
    height = img.shape[0]
    width = img.shape[1]
    channels = img.shape[2]

    print('Image Dimension    : ', dimensions)
    print('Image Height       : ', height)
    print('Image Width        : ', width)
    print('Number of Channels : ', channels)

    # Start coordinate, here (400, 200)
    # represents the top left corner of rectangle
    start_point = (400, 200)

    # Ending coordinate, here (800, 600)
    # represents the bottom right corner of rectangle
    end_point = (800, 600)

    # Blue color in BGR
    color = (255, 0, 0)

    # Line thickness of -1 px
    # Thickness of -1 will fill the entire shape
    thickness = -1

    # Using cv2.rectangle() method
    # Draw a rectangle of black color of thickness -1 px
    img = cv2.rectangle(img, start_point, end_point, color, thickness)

    tmp_directory = current_directory + "/tmp"
    if not os.path.exists(tmp_directory):
        os.makedirs(tmp_directory)

    cv2.namedWindow("Press ESC on keyboard to exit.", cv2.WINDOW_NORMAL)

    # Display the resulting frame
    cv2.imshow("Press ESC on keyboard to exit.", img)

    k = cv2.waitKey(0)
    if k == 27:  # wait for ESC key to exit
        pass
    elif k == ord('s'):  # wait for 's' key to save and exit
        image_name = "%s/%s.jpg" % (tmp_directory, "source_image")
        cv2.imwrite(image_name, img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])

    # When everything done, release the capture
    cv2.destroyAllWindows()


if __name__ == '__main__':
    image_file = "./tmp/000505.jpg"

    os.environ["CUDA_VISIBLE_DEVICES"] = '0'
    print("os.environ['CUDA_VISIBLE_DEVICES']:", os.environ['CUDA_VISIBLE_DEVICES'])

    inference(image_file, current_directory)

OpenCV 3 drawing rectangle - 绘制 rectangle

/usr/bin/python2.7 /home/strong/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow/yongqiang.py --gpu=0
os.environ['CUDA_VISIBLE_DEVICES']: 0
Image Dimension    :  (1080, 1920, 3)
Image Height       :  1080
Image Width        :  1920
Number of Channels :  3

Process finished with exit code 0

3.3 cv2.FILLED

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Yongqiang Cheng

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

import os
import sys

sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
current_directory = os.path.dirname(os.path.abspath(__file__))

import numpy as np
# import tensorflow as tf
import cv2


# import time


def inference(image_file, current_directory):
    img = cv2.imread(image_file, cv2.IMREAD_COLOR)

    # get dimensions of image
    dimensions = img.shape

    # height, width, number of channels in image
    height = img.shape[0]
    width = img.shape[1]
    channels = img.shape[2]

    print('Image Dimension    : ', dimensions)
    print('Image Height       : ', height)
    print('Image Width        : ', width)
    print('Number of Channels : ', channels)

    # Start coordinate, here (400, 200)
    # represents the top left corner of rectangle
    start_point = (400, 200)

    # Ending coordinate, here (800, 600)
    # represents the bottom right corner of rectangle
    end_point = (800, 600)

    # Blue color in BGR
    color = (255, 0, 0)

    # Line thickness of -1 px
    # Thickness of -1 will fill the entire shape
    thickness = -1

    # Using cv2.rectangle() method
    # Draw a rectangle of black color of thickness -1 px
    img = cv2.rectangle(img, start_point, end_point, color, cv2.FILLED)

    tmp_directory = current_directory + "/tmp"
    if not os.path.exists(tmp_directory):
        os.makedirs(tmp_directory)

    cv2.namedWindow("Press ESC on keyboard to exit.", cv2.WINDOW_NORMAL)

    # Display the resulting frame
    cv2.imshow("Press ESC on keyboard to exit.", img)

    k = cv2.waitKey(0)
    if k == 27:  # wait for ESC key to exit
        pass
    elif k == ord('s'):  # wait for 's' key to save and exit
        image_name = "%s/%s.jpg" % (tmp_directory, "source_image")
        cv2.imwrite(image_name, img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])

    # When everything done, release the capture
    cv2.destroyAllWindows()


if __name__ == '__main__':
    image_file = "./tmp/000505.jpg"

    os.environ["CUDA_VISIBLE_DEVICES"] = '0'
    print("os.environ['CUDA_VISIBLE_DEVICES']:", os.environ['CUDA_VISIBLE_DEVICES'])

    inference(image_file, current_directory)

OpenCV 3 drawing rectangle - 绘制 rectangle

/usr/bin/python2.7 /home/strong/tensorflow_work/R2CNN_Faster-RCNN_Tensorflow/yongqiang.py --gpu=0
os.environ['CUDA_VISIBLE_DEVICES']: 0
Image Dimension    :  (1080, 1920, 3)
Image Height       :  1080
Image Width        :  1920
Number of Channels :  3

Process finished with exit code 0