Micah P. Dombrowski / Jun 16 2020
OpenCV Python Example

A short example of using OpenCV on Nextjournal, adapted from code by Shantnu Tiwari. The default Python environment includes the opencv-python-headless package, as we cannot support OpenCV's GUI functions such as imshow(); thus, the primary difference is using imwrite() instead.
import cv2import sys# Get user supplied valuesimagePath = abba.pngcascPath = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"# Create the haar cascadefaceCascade = cv2.CascadeClassifier(cascPath)# Read the imageimage = cv2.imread(imagePath)gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Detect faces in the imagefaces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30) #flags = cv2.CV_HAAR_SCALE_IMAGE)print("Found {0} faces!".format(len(faces)))# Draw a rectangle around the facesfor (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)cv2.imwrite("/results/abba-faces.png", image)0.9s
Python
True