Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Python type casting

Good day gents,

I got code from the net at this page for simple face recognition. I am playing around with it at the moment like adding text and circles etc.

I want to find the center point of each rectangle (face) that is drawn on the frame. However I keep on getting "

TypeError: cannot concatenate 'str' and 'int' objects

Here is my code:

import cv2
import math

# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# To capture video from webcam. 
cap = cv2.VideoCapture(0)
# To use a video file as input 
# cap = cv2.VideoCapture('filename.mp4')
#Text Stuff
rectangleThicknes = 1
videoCenterCircleColor = (0, 255, 0)
videoCenterCircleThickness = 1
rectangleCenterCircleColour = (255, 0, 0)
rectangleCenterCircleThickness = 1

while True:
    # Read the frame
    _, img = cap.read()
    #Draw a circle in the middle of the video
    circle = cv2.circle(img, (320, 210), 5, videoCenterCircleColor, videoCenterCircleThickness)
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Detect the faces
    faces = face_cascade.detectMultiScale(gray, 1.1, 4)
    # Draw the rectangle around each face
    for (x, y, w, h) in faces:
        ###Start finding "x, y, w, h"###
        rectangleXposition = format(x)
        rectangleYposition = format(y)
        rectangleWidth = format(w)
        rectangleHeight = format(h)
        rectangleHalfWidth = int(rectangleWidth) / 2
        rectangleHalfHeight = int(rectangleHeight) / 2
        rectangleCenterXaxis = format(rectangleXposition + rectangleHalfWidth)
        rectangleCenterYaxis = format(rectangleYposition + rectangleHalfHeight)
        ###End finding "x, y, w, h"###

        #Draw a circle in the center of the rectangle around the face
        circle = cv2.circle(img, (rectangleCenterXaxis, rectangleCenterYaxis), 5, rectangleCenterCircleColour, rectangleCenterCircleThickness)
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), rectangleThicknes)
    # Display
    cv2.imshow('img', img)
    # Stop if escape key is pressed
    k = cv2.waitKey(30) & 0xff
    if k==27:
        break
# Release the VideoCapture object
cap.release()