Python draw rectangle on image

Binary Study

OpenCV (Open Source Computer Vision) is an open source computer vision library. To work with computer vision problems OpenCV is very helpful. We can perform many tasks using OpenCV like Recognition, Motion Analysis, Scene Reconstruction, image restoration.

We use cv2.rectangle() to draw rectangle on an image. This method is used to draw bounding boxes of the objects in object detection task.

Table of Contents:

Prerequisites:

Install OpenCV

If you have not already installed OpenCV on you system, you can install it using pip command as written below.

Syntax

The syntax to draw rectangle on an image is as below.

cv2.rectangle(image, start_point, end_point, color, thickness)
Parameters:
image: image on that the rectangle to drawn
start_point:(width_min, height_min)= (xmin, ymin):start coordinate of rectangle. It is top left point on the image.
end_point: (width_max, height_max)= (xmax, yax):end coordinate of rectangle. It’s bottom right point on the image.
color: (B,G,R)- Color of the line
thickness: Thickness of the line

Steps

  1. Load the image
  2. define starting and ending point of the rectangle
  3. Define the color of the line of the rectangle
  4. Define the thickness of the line of the rectangle
  5. Draw the rectangle
  6. Display the image with drawn rectangle

Example 1.

Let’s write complete Python 3 program for drawing rectangle on the image.

# Python 3 program to draw rectangle on an image

# import cv2
import cv2

# Read an image
img = cv2.imread('Koala.jpg')

# Start coordinate (xmin, ymin), it represents the top left corner of rectangle
start_point = (320, 200)

# End coordinate (xmax, ymax), it represents the bottom right corner of rectangle
end_point = (800, 650)

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

# Line thickness of 4 px
thickness = 4

# Using cv2.rectangle()
# Draw a rectangle with green line of thickness of 4 px
img = cv2.rectangle(img, start_point, end_point, color, thickness)

# Display the image
cv2.imshow("Koala", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Example 2.

If we use thickness as -1, it will fill whole rectangle with the chosen line color. Here we take green color to draw the rectangle but using thickness as -1, so the whole rectangle is filled with green color.

# Python 3 program to draw rectangle on an image

# import cv2
import cv2

# Read an image
img = cv2.imread('Koala.jpg')

# Start coordinate (xmin, ymin), it represents the top left corner of rectangle
start_point = (320, 200)

# End coordinate (xmax, ymax), it represents the bottom right corner of rectangle
end_point = (800, 650)

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

# Line thickness of -1 px
thickness = -1

# Using cv2.rectangle()
# Draw a rectangle with green line of thickness of 4 px
img = cv2.rectangle(img, start_point, end_point, color, thickness)

# Display the image
cv2.imshow("Koala", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Further Readings:

Useful Resources:

Источник

Читайте также:  Vue global css variable

Python OpenCV: how to draw rectangles on an image

In this post we are going to learn how to draw rectangles on an image, using Python and OpenCV.

OpenCV offers us a couple of functions to draw shapes on images, as can be seen here. These may be interesting to highlight regions of interest. For example, if we are applying an algorithm to detect faces, a simple way to signal them can be drawing a rectangle around them.

This tutorial was tested on Windows 8.1, with version 4.1.2 of OpenCV. The Python version used was 3.7.2.

Drawing the Rectangles

The first line of our code will be for importing the cv2 module, so we have access to the function we need to draw rectangles on images.

Next, we will take care of reading an image from the file system. We do so with a call to the imread function. As input we pass the path to the image and, as output, the function returns the image as a ndarray. When testing the code, don’t forget to update the path to an image in your file system.

img = cv2.imread('C:/Users/N/Desktop/monument.png')

Now that we have our image in memory, we will draw some rectangles on it. To draw a rectangle with OpenCV, we simply need to use the rectangle function. This function receives the following arguments:

  • The image where to draw the rectangle. We will pass the image we just read;
  • A tuple with the x and y coordinates of one of the vertices of the rectangle. To simplify the drawing of the shape, it is easier to always think about this vertex as the top left corner of the rectangle;
  • A tuple with the x and y coordinates of the opposite vertex of the rectangle, regarding the previous one. Also to simplify, we can consider this the bottom right corner of the rectangle;
  • A tuple with the BGR color of the rectangle;
  • Thickness of the lines of the rectangle. It is an optional parameter that, when not specified, defaults to 1. Also, negative numbers will result in a filled rectangle being drawn.

It’s important to consider that the rectangle function alters the image we pass as input. This means that, if we want to keep the original image unaltered, we should do a copy of it and draw the rectangle on that copy. To learn how to perform a copy of an image in memory with OpenCV, please consult this post.

Now that we have analyzed all the arguments of the rectangle function of the cv2 module, we will draw the first shape. We will draw it between (x=10, y=10) and (x=100, y=100), in green color. Also, to illustrate that the thickness is optional, we won’t set this value.

cv2.rectangle(img, (10, 10), (100, 100), (0, 255, 0))

We will draw a second rectangle, this time between (x=120, y=120) and (x=150, y=150). The color will be blue this time and we will set the thickness of the lines of the rectangle to 5 pixels.

cv2.rectangle(img, (120, 120), (150, 150), (255, 0, 0), 5)

Our final rectangle will be between the coordinates (x=200, y=200) and (x=300, y=400) and drawn in red. We will also set the thickness to a negative number, so it is drawn as a filled shape.

cv2.rectangle(img, (200, 200), (300, 400), (0, 0, 255), -1)

Important: The coordinates I’ve used to draw the previous three rectangles are adequate for the size of the image I’m using. Depending on the image you will be using for your tests, you may need to use different coordinates for the rectangles to fit inside.

Читайте также:  On page load event html

Now that we have finished drawing over our image, we will display it in an OpenCV window. This is done with a call to the imshow function, passing as first input the name of the window and as second our image.

To finalize, we will wait for the user to press any key on the keyboard and, when that happens, destroy the window and end the program.

cv2.waitKey(0) cv2.destroyAllWindows()

The complete Python code can be seen below.

import cv2 img = cv2.imread('C:/Users/N/Desktop/monument.png') cv2.rectangle(img, (10, 10), (100, 100), (0, 255, 0)) cv2.rectangle(img, (120, 120), (150, 150), (255, 0, 0), 5) cv2.rectangle(img, (200, 200), (300, 400), (0, 0, 255), -1) cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()

Testing the code

To test the previous Python script, simply run it in a tool of your choice. I’ll be using PyCharm, a Python IDE.

Upon running the code, you should get a result similar to the one illustrated in figure 1. As can be seen, we got three rectangles in the image. The first one is drawn in green, with a width of 1 pixel. The second one is drawn in blue and with thicker lines. The third one is drawn in red and it is a filled rectangle. The three are drawn between the coordinates we specified in our code, as expected.

Final image, with the three rectangles drawn.

Suggested OpenCV readings

Источник

Draw a rectangle on an image using OpenCV in Python

In this tutorial, we will learn some simple techniques to draw a rectangle on an image using OpenCV in Python. By the end of this tutorial, you will learn how to draw a rectangle and you will also be able to draw other polygons with ease.

This will help to outline the region of interest whenever we want to highlight a particular region. So, let’s begin the tutorial

Install OpenCV

This is the prerequisite to proceed to use OpenCV. If you have not installed it, you can install it by using the below command in the command prompt.

cv2.rectangle() to draw a rectangle on an image in Python

First, we will read the input image using the method cv2.imread(). This method takes the argument as the name of the input image with extension.

Читайте также:  Глобальные стили

Draw a rectangle on an image in Python using OpenCV

Then we use cv2.rectangle() method. This method takes 5 arguments:

input_image is the image on which the rectangle is to be drawn.

start_coordinates point to the top corner of the rectangle.

end_coordinates point to the bottom corner of the rectangle.

color is specified in BGR format

thickness is used to specify the width of the outer border.

img = cv2.rectangle(img, (200,450), (450,210), (0,0,255), 3)

The final image with a rectangle is displayed using cv2.imshow(). This method takes 2 arguments. The first is the label of the output image. The second argument is the image that is to be displayed. The image will be displayed until there is an interrupt from the keyboard by the user. This is done by using the cv2.waitKey() method. At last, the window is destroyed by using the method cv2.destroyAllWindows(). Putting everything together we have,

import cv2 img = cv2.imread("caa.JPG") img = cv2.rectangle(img, (200,450), (450,210), (0,0,255), 3) cv2.imshow("rectangle", img) cv2.waitKey() cv2.destroyAllWindows()

Using cv2.line()

From the basic definition of a rectangle, 4 line segments together form a rectangle. The same concept is used in this section. This method takes 5 arguments.

All the arguments are the same as the arguments of the previous method with a small difference. Here, only a line segment is drawn from start_coordinate to end_coordinate.To form a complete rectangle, we need 4 such line segments.

img = cv2.line(img, (200,480), (440,480), (0,0,255), 3)

Draw lines such that, length=breadth i.e, the distance between 2 sides should be the same and the other 2 sides should also be the same. Then display the final image using the method cv2.imshow(). The final code is

import cv2 img = cv2.imread("caa.JPG") img = cv2.line(img, (200,480), (440,480), (0,0,255), 3) img = cv2.line(img, (200,220), (200,480), (0,0,255), 3) img = cv2.line(img, (200,220), (440,220), (0,0,255), 3) img = cv2.line(img, (440,220), (440,480), (0,0,255), 3) cv2.imshow("rectangle", img) cv2.waitKey() cv2.destroyAllWindows()

Using cv2.polylines()

This method is used to draw multiple lines. This method consists of an array that has the coordinates of all the points to be connected. To access the array, we import NumPy.This method takes 5 arguments

input_image is the image on which the rectangle is to be drawn

[array] takes the coordinate values

True/False Indicate whether the figure should be opened or closed. True indicates closed. False indicates open.

color and thickness are the same as the previous methods.

import cv2 import numpy as rect img = cv2.imread("caa.JPG") coordinates = rect.array([[200,480], [200,220], [440,220], [440,480] ]) cv2.polylines(img, [coordinates], True, (0,0,255),3) cv2.imshow("rectangle", img) cv2.waitKey() cv2.destroyAllWindows()

Output

The final output of all three codes is the same and it is as given below,

Draw a rectangle on an image in Python using OpenCV

So we have seen three different ways to draw a rectangle on an image with OpenCV Python.

2 responses to “Draw a rectangle on an image using OpenCV in Python”

Traceback (most recent call last):
File “C14.py”, line 6, in
cv2.imshow(“rectangle”, img)
cv2.error: OpenCV(4.2.0) ../modules/highgui/src/window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function ‘imshow’
## I am getting this error

Источник

Оцените статью