Life2Coding
Drawing Fancy Round Rectangle Around Face using OpenCV Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply them in various aspects using some great examples. Then the output will be visualized along with the comparisons.

We will also discuss the basic of image processing and provide the detail explanation related to the OpenCV functions.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV with Python 3

Goals:

The goal is to make you understand how to draw custom rectangle around detected face using Python OpenCV function works.

Download Face Haar Cascade: Face Cascade

Documentation:

line()

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

Draws a line segment connecting two points.

Parameters
img Image.
pt1 First point of the line segment.
pt2 Second point of the line segment.
color Line color.
thickness Line thickness.
lineType Type of the line. See LineTypes.
shift Number of fractional bits in the point coordinates.

ellipse()

img=cv.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]])
img=cv.ellipse(img, box, color[, thickness[, lineType]])
img=cv.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]])
img=cv.ellipse(img, box, color[, thickness[, lineType]])

Draws a simple or thick elliptic arc or fills an ellipse sector.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
img Image.
center Center of the ellipse.
axes Half of the size of the ellipse main axes.
angle Ellipse rotation angle in degrees.
startAngle Starting angle of the elliptic arc in degrees.
endAngle Ending angle of the elliptic arc in degrees.
color Ellipse color.
thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that a filled ellipse sector is to be drawn.
lineType Type of the ellipse boundary. See LineTypes
shift Number of fractional bits in the coordinates of the center and values of axes.
Parameters
img Image.
box Alternative ellipse representation via RotatedRect. This means that the function draws an ellipse inscribed in the rotated rectangle.
color Ellipse color.
thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that a filled ellipse sector is to be drawn.
lineType Type of the ellipse boundary. See LineTypes

imread()

retval=cv.imread(filename[, flags])

Loads an image from a file.

Parameters
filename Name of file to be loaded.
flags Flag that can take values of cv::ImreadModes

cvtColor()

dst=cv.cvtColor(src, code[, dst[, dstCn]])

Converts an image from one color space to another.

Parameters
src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.
dst output image of the same size and depth as src.
code color space conversion code (see ColorConversionCodes).
dstCn number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code.

imshow()

None=cv.imshow(winname, mat)

Displays an image in the specified window.

Parameters
winname Name of the window.
mat Image to be shown.

waitKey()

retval=cv.waitKey([, delay])

Waits for a pressed key.

Parameters
delay Delay in milliseconds. 0 is the special value that means “forever”.

destroyAllWindows()

None=cv.destroyAllWindows()

Destroys all of the HighGUI windows.

Steps:

  • Load a face image using cv2.imread()
  • Create face cascade classifier using cv2.CascadeClassifier()
  • Detect face rectangle using cv2.detectMultiScale()
  • Then draw custom lines using cv2.line()
  • Also create ellipse using cv2.ellipse()
  • Display all the images using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2

def draw_border(img, pt1, pt2, color, thickness, r, d):
    x1,y1 = pt1
    x2,y2 = pt2

    # Top left
    cv2.line(img, (x1 + r, y1), (x1 + r + d, y1), color, thickness)
    cv2.line(img, (x1, y1 + r), (x1, y1 + r + d), color, thickness)
    cv2.ellipse(img, (x1 + r, y1 + r), (r, r), 180, 0, 90, color, thickness)

    # Top right
    cv2.line(img, (x2 - r, y1), (x2 - r - d, y1), color, thickness)
    cv2.line(img, (x2, y1 + r), (x2, y1 + r + d), color, thickness)
    cv2.ellipse(img, (x2 - r, y1 + r), (r, r), 270, 0, 90, color, thickness)

    # Bottom left
    cv2.line(img, (x1 + r, y2), (x1 + r + d, y2), color, thickness)
    cv2.line(img, (x1, y2 - r), (x1, y2 - r - d), color, thickness)
    cv2.ellipse(img, (x1 + r, y2 - r), (r, r), 90, 0, 90, color, thickness)

    # Bottom right
    cv2.line(img, (x2 - r, y2), (x2 - r - d, y2), color, thickness)
    cv2.line(img, (x2, y2 - r), (x2, y2 - r - d), color, thickness)
    cv2.ellipse(img, (x2 - r, y2 - r), (r, r), 0, 0, 90, color, thickness)


def detect(path,img):
    cascade = cv2.CascadeClassifier(path)

    img=cv2.imread(img,1)
    # converting to gray image for faster video processing
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    rects = cascade.detectMultiScale(gray, 1.2, 3,minSize=(50, 50))
    # if at least 1 face detected
    if len(rects) >= 0:
        # Draw a rectangle around the faces
        for (x, y, w, h) in rects:
            draw_border(img, (x, y), (x + w, y + h), (255, 0, 105),4, 15, 10)
        # Display the resulting frame
        cv2.imshow('Face Detection', img)
        # wait for 'c' to close the application
        cv2.waitKey(0)


def main():
    cascadeFilePath = "./haar/haarcascade_frontalface_default.xml"
    img='./hanif.jpg'
    detect(cascadeFilePath,img)
    cv2.destroyAllWindows()


if __name__ == "__main__":
    main()

Output:

5cd107414c190 Drawing Fancy Round Rectangle Around Face using OpenCV Python
life2coding_icon [] Drawing Fancy Round Rectangle Around Face using OpenCV Python
Latest posts by Life2Coding (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.