3 basic examples of opencv-python --- display pictures, draw graphics, face recognition


The contents are referred to the instructions on the official website:  http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_tutorials.html


Show Image -Gui Features in OpenCV-


# display image
import cv2


img = cv2.imread("./animal.jpg", cv2.IMREAD_COLOR )
cv2.namedWindow("Image")
cv2.imshow("Image", img)

print "save press s, exit press esc"
key = cv2.waitKey (0)

if key == 27:
    cv2.destroyAllWindows()
elif key == ord('s'):
    cv2.imwrite("wirte.png", img)
    cv2.destroyAllWindows()




Drawing Graphics -Gui Features in OpenCV-

# drawing

import numpy
import cv2

# Create a black image
img = numpy.zeros((512,512,3), numpy.uint8)

# Draw a diagonal blue line with thickness of 5 px
cv2.line(img,(0,0),(511,511),(255,0,0),5)

# draw a rectangle
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)

# draw a circle
cv2.circle(img,(447,63), 63, (0,0,255), -1)

# add text
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'Meng', (10,500), font, 4, (255,255,255), 2)
# cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)   # cv2.LINE_AA not found

# write file to disk
# cv2.namedWindow("Image")

cv2.imshow("Image", img)
key = cv2.waitKey (0)
cv2.destroyAllWindows()



3. Face Recognition


For details on how to train, see the document. Here we teach you how to use the trained xml file.

haarcascade_frontalface_default.xml
haarcascade_eye.xml
These two files are in the decompressed source code path opencv-3.2.0/data/haarcascades/ directory, just copy it manually, the code is as follows

# face detection

import numpy
import cv2

face_cascade = cv2.CascadeClassifier("data/haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier ('data / haarcascade_eye.xml')

img = cv2.imread("wbq.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

The effect is slightly biased, such as the picture of Brother Dafeng.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324969705&siteId=291194637