How to use cv2.rectangle() method

share link

by vinitha@openweaver.com dot icon Updated: Oct 4, 2023

technology logo
technology logo

Solution Kit Solution Kit  

OpenCV is an Open-Source Computer Vision and ML software library. Intel originally developed it, and is now maintained by a community of developers.  


OpenCV provides various tools and functions for performing various tasks. OpenCV module provides several functions and methods to work with rectangles. Computer vision problems use rectangles for tasks such as object detection. OpenCV allows you to create rectangles of different sizes and orientations. 


Here are some of the key types of rectangles you can work with in OpenCV python:  

  • Axis-Aligned Rectangles  
  • Rotated Rectangles  
  • Bounding Boxes  


In OpenCV, you can create rectangles using various rectangle functions. Here are some of the different methods to create rectangles with OpenCV:  

  • cv2.rectangle(): This is the most common method to draw rectangles on images in OpenCV.  
  • cv2.findContours(): find the contours of objects in binary images.  
  • cv2.boundingRect(): create bounding rectangles around these objects  


OpenCV can process rectangles in various ways depending on the task at hand. Two commonly used modules for processing rectangles are:  

  • Matcher module: The matcher module uses object detection and matching.  
  • Tracker module: The object tracking module uses the Tracker module.  


To summarize, we use OpenCV to create multiple rectangles. The toolkit is helpful for various computer vision and image processing tasks. For people in the field, it is very useful and reliable. It enables the development of innovative and reliable computer vision applications.  

Fig: Preview of the output that you will get on running this code from your IDE

Code

In this solution we are using open cv library

import cv2
import numpy as np

drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle.
ix,iy = -1,-1

# mouse callback function
def draw_circle(event,x,y,flags,param):
  global ix,iy,drawing,mode

  if event == cv2.EVENT_LBUTTONDOWN:
      drawing = True
      ix,iy = x,y

  elif event == cv2.EVENT_MOUSEMOVE:
    if drawing == True:
        if mode == True:
            cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),3)
            a=x
            b=y
            if a != x | b != y:
                 cv2.rectangle(img,(ix,iy),(x,y),(0,0,0),-1)
        else:
            cv2.circle(img,(x,y),5,(0,0,255),-1)

  elif event == cv2.EVENT_LBUTTONUP:
    drawing = False
    if mode == True:
        cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),2)

    else:
        cv2.circle(img,(x,y),5,(0,0,255),-1)

img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

while(1):
 cv2.imshow('image',img)
 k = cv2.waitKey(1) & 0xFF
 if k == ord('m'):
    mode = not mode
 elif k == 27:
    break

cv2.destroyAllWindows()   

# import the necessary packages
import cv2
import argparse

# now let's initialize the list of reference point
ref_point = []

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

    # if the left mouse button was clicked, record the starting
    # (x, y) coordinates and indicate that cropping is being performed
    if event == cv2.EVENT_LBUTTONDOWN:
        ref_point = [(x, y)]

    # check to see if the left mouse button was released
    elif event == cv2.EVENT_LBUTTONUP:
        # record the ending (x, y) coordinates and indicate that
        # the cropping operation is finished
        ref_point.append((x, y))

        # draw a rectangle around the region of interest
        cv2.rectangle(image, ref_point[0], ref_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="Path to the image")
args = vars(ap.parse_args())

# load the image, clone it, and setup the mouse callback function
image = cv2.imread(args["image"])
clone = image.copy()
cv2.namedWindow("image")
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 the window
    if key == ord("r"):
        image = clone.copy()

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

# close all open windows
cv2.destroyAllWindows() 

Instructions

Follow the steps carefully to get the output easily.


  1. Download and Install the PyCharm Community Edition on your computer.
  2. Open the terminal and install the required libraries with the following commands.
  3. Create a new Python file on your IDE.
  4. Copy the snippet using the 'copy' button and paste it into your python file.
  5. Remove the code line 48 to last line of code for better understanding
  6. Run the current file to generate the output.


I hope you found this useful.


I found this code snippet by searching for ' drawing rectangle in openCV python ' in Kandi. You can try any such use case!

Environment tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. PyCharm Community Edition 2023.1
  2. The solution is created in Python 3.11.1 Version
  3. Open CV 0.7.2 version



Using this solution, we can able to use cv2.rectangle() method with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to use cv2.rectangle() method.

Dependency library

keypressby TooTallNate

JavaScript doticonstar image 330 doticonVersion:Currentdoticon
no licences License: No License (null)

Make any Node ReadableStream emit "keypress" events

Support
    Quality
      Security
        License
          Reuse

            keypressby TooTallNate

            JavaScript doticon star image 330 doticonVersion:Currentdoticonno licences License: No License

            Make any Node ReadableStream emit "keypress" events
            Support
              Quality
                Security
                  License
                    Reuse

                      globalby Raynos

                      JavaScript doticonstar image 234 doticonVersion:Currentdoticon
                      License: Permissive (MIT)

                      Require global variables

                      Support
                        Quality
                          Security
                            License
                              Reuse

                                globalby Raynos

                                JavaScript doticon star image 234 doticonVersion:Currentdoticon License: Permissive (MIT)

                                Require global variables
                                Support
                                  Quality
                                    Security
                                      License
                                        Reuse

                                          You can search for any dependent library on kandi like ' keypress' ' global '.

                                          FAQ:  

                                          1. What is Open-Source Computer Vision (OpenCV), and why is it useful?  

                                          Open-Source Computer Vision is an open-source computer vision and machine learning library. This framework offers many tools for computer vision tasks. Intel initially created OpenCV, but a group of developers now supports it. 

                                          Here's why OpenCV is useful:  

                                          • Versatility  
                                          • Open Source  
                                          • Cross-Platform  


                                          2. How can I use the OpenCV Python library to draw a rectangle on an image?  

                                          You can use the OpenCV Python library to draw a rectangle on an image using the cv2.rectangle() function. With this function, you can choose the image, color, and thickness of the rectangle's border. 

                                          Here's a step-by-step guide on how to do it:   

                                          • Import the OpenCV library  
                                          • Read the image on which you want to draw the rectangle  
                                          • Define the coordinates of the top-left and bottom-right corners of the rectangle  
                                          • Define the color of the rectangle.  
                                          • Define the thickness of the rectangle's border  
                                          • Draw the rectangle on the image using the cv2.rectangle() function  


                                          3. Can OpenCV draw only a green rectangle?  

                                          You can draw a green rectangle using OpenCV by specifying the color in the BGR (Blue, Green, Red) color space. In the BGR color space, (0, 255, 0) represents a green color. This means the green component is at its highest, while the blue and red components are at zero.  


                                          4. How do I create a green rectangle on an image using OpenCV?  

                                          You can use the cv2.rectangle() function, which allows you to specify the rectangle's color. Here's how you can do it in Python:  

                                          • Import the OpenCV library  
                                          • Read the image on which you want to draw the green rectangle  
                                          • Define the coordinates of the top-left and bottom-right corners of the rectangle  
                                          • Define the color of the rectangle  
                                          • Define the thickness of the rectangle's border  
                                          • Draw the green rectangle on the image using the cv2.rectangle() function  
                                          • Display the image with the green rectangle  


                                          5. What syntax is for importing Numpy into my code to use drawing functions with OpenCV?  

                                          Import both libraries to use drawing functions in OpenCV and NumPy in your Python code. Here's the syntax for importing both OpenCV and NumPy in your code:   

                                          import cv2  

                                          import numpy as np  

                                          # Now you can use OpenCV's drawing functions and NumPy arrays together  

                                          Support

                                          1. For any support on kandi solution kits, please use the chat
                                          2. For further learning resources, visit the Open Weaver Community learning page

                                          See similar Kits and Libraries