opencv-python
Reading images
img = cv2.imread("path/to/image/file.jpg")
# img is a numpy array
img = cv2.imread("path/to/image/file.jpg", 0)
# 0 => grayscale, 1 => bgr, -1 => preserve alpha values
Creating images
cv2.imwrite("path/to/file.jpg", old_img)
Resizing images
cv2.resize(image, (width, height))
Detecting face
To detect face, we need some models that will be used by the cv2 to process the image and detect face.
For example, haarcascade_frontalface_default.xml
is a model
face_cascade = cv2.cascadeClassifier("haarcascade_frontalface_default.xml")
results = face_cascade.detectMultiScale(img, scaleFactor=1.05, minNeighbors=5)
results
is an 2d array of detected positions.
[
[x, y, width, height]
]
Drawing rectangle
This positions can be used to draw rectangle around faces
for x, y, w, h in results:
img = cv2.rectangle(img, (x, y), (x + w, y + h), 3)
Showing image
cv2.imshow("Image", img)
cv2.waitKey(0) # wait for key '0' to press
cv2.destroyAllWindows() # after pressing '0' the image window will get closed
waitKey
method wait for user key press on the image window. It takes parameter time in milliseconds to wait for the key. If it’s 0
then wait forever.
It returns the ascii value key pressed.
Video processing from webcam
video = cv2.VideoCapture(0) # 0 is the camera number
has_frame, frame = vide.read()
video.realase() # release the camera control
Blurring Images
img = cv.GaussianBlur(img, (21, 21), 0)