opencv-python 基本例子3个

2023-01-31 02:01:33 opencv


其中的内容均参考自官网的说明: Http://docs.OpenCV.org/3.0-beta/doc/py_tutorials/py_tutorials.html


显示图片-Gui Features in OpenCV-

  • Getting Started with Images

# 显示图片
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()




绘制图形-Gui Features in OpenCV-
  • Drawing Functions 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.人脸识别

参考文档: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_objdetect/py_face_detection/py_face_detection.html#face-detection

其中具体如何训练见文档,这里教大家如何使用训练好的xml文件。

haarcascade_frontalface_default.xml
haarcascade_eye.xml
这两个文件在解压的源代码路径 opencv-3.2.0/data/haarcascades/ 目录下,手动拷贝一下就可以了,代码如下

# 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()

效果稍微有点偏差,比如说大峰哥这个图。

相关文章