Create a window, display an image, mark an image, move a camera, and recognize a face.

This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together

On day 11 after the initial test, we will simply learn the basic operation of OpencV to prepare for the final design.


Environment: Jupyter Notebook Language: Python You need to download the OpencV library in advance

Guide package

import cv2
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline 
Copy the code

Opencv window basic operations

Create a window

cv2.namedWindow("window",cv2.WINDOW_NORMAL)

  • The first parameter is the name of the window
  • The second parameter is the size type of the window, which can be viewed in the source code, usually usedcv2.WINDOW_NORMALwithcv2.WINDOW_AUTOSIZEThe former can be manually resized, while the latter can be adaptive


Modify window size

Cv2. ResizeWindow (' window ', 800600)


Display the specified window

cv2.imshow('window',0)


Specifies the keystroke destruction window

  • cv2.waitKey(0)Returns the ASCII value of the key, with the argument 0 to accept any key and some other integer to indicate the time to wait for the key in milliseconds.
  • cv2.destroyAllWindows()Close all Windows opened by this thread

Comprehensive use of

key = cv2.waitKey(0)
if key == ord('q') :# ord converts a character to its corresponding ASCII code
    cv2.destroyAllWindows()
Copy the code

All the code

Create window
cv2.namedWindow("window",cv2.WINDOW_AUTOSIZE) # WINDOW_AUTOSIZE Does not allow window sizes to be changed
cv2.namedWindow("window",cv2.WINDOW_NORMAL)

# Change the window size
cv2.resizeWindow('window'.800.600)
# display the window named window
cv2.imshow('window'.0)

Ord ('q') -> 113
# waitKey returns the ASCII value of the key. The argument is 0 to accept any key, and the other integers are milliseconds to wait for the key
You can use waitKey to destroy the window instead of destroying it every time
key = cv2.waitKey(0)
Select the first eight bits and compare them with ASCII
if key & 0xFF= =ord('q') :# we can omit &0xff
# if key == ord('q'): 
    cv2.destroyAllWindows()
Copy the code

Opencv displays image manipulation

Use the imread function to read the current picture

rose = cv2.imread('./rose.jpeg')
rose.shape # (610, 610, 3)
type(rose)
Copy the code

Display images (using opencV’s built-in functions)

Opencv reads BGR channels, not traditional RGB using imshow using matplotlib will result in different results from the original image

# matplotlib displays a different color from the real image
plt.imshow(rose)
Copy the code

# So opencV reads images in their own way
cv2.imshow('rose',rose)
key = cv2.waitKey(0)
if key == ord('q'): 
    cv2.destroyAllWindows()
Copy the code

Encapsulates the function that displays the picture. By default, press Q to exit

# Wrap the function, show the picture
def cv_show(name,img) :
    cv2.imshow(name,img)
    key = cv2.waitKey(0)
    if key & 0xFF= =ord('q'): 
        cv2.destroyAllWindows()
Copy the code

Store the image

cv2.imwrite('tong.jpg',img)
Copy the code

Opencv marks image manipulation

First draw a blank black background, then complete the basic drawing of lines, circles, marks etc. Note: for the order of coordinates in OpenCV, see the drawing below

# Create a solid black background for drawing
img = np.zeros((480.640.3),np.uint8)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy the code

Drawing background plate Line drawing

Cv2. Line (img, (10, 20), (300400), (0,0,255), 5)

Give the starting point, end point, color and thickness respectively Draw a rectangular

Cv2. A rectangle (img, (10, 20), (300400), (0,0,255), 5)

Give the upper left and lower right endpoints, color and thickness respectively

A circle

V2. Circle (img, (320240), 100, (0,0,255), 5)

Annotation text

Chinese cannot be displayed in OpencV, you need to use PIL library to display Chinese, see below

cv2.putText(img,'Hello OpenCV', (50.400),cv2.FONT_HERSHEY_COMPLEX,2[0.0.255])
Copy the code

Chinese annotation text

You need to prepare your font files in advance

# Resolve Chinese display garbled characters
from PIL import ImageFont,ImageDraw,Image
# img = np.full((200, 200, 3),fill_value=255,dtype=np.uint8)
img = cv2.imread('./rose.jpeg')
font = ImageFont.truetype('./msyhbd.ttc'.15)
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
draw.text((100.350),'Hello, hello, hello, hello.', font = font,fill=(0.255.0.0))
img = np.array(img_pil)
cv_show('img',img)
Copy the code


The complete code

# Create a solid black background for drawing
img = np.zeros((480.640.3),np.uint8)
Draw a line #
cv2.line(img, (10.20), (300.400), (0.0.255), 5)
# draw rectangle
cv2.rectangle(img, (10.20), (300.400), (0.0.255), 5)
# Draw circle parameters: center coordinates, radius size, color, thickness
cv2.circle(img, (320.240),100, (0.0.255), 5)
# picture words
cv2.putText(img,'Hello OpenCV', (50.400),cv2.FONT_HERSHEY_COMPLEX,2[0.0.255])
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy the code

Opencv calls camera operations

Cv2.imwrite (‘ tongs. JPG ‘,frame)

Frame stores the image captured by the camera. Cv2.waitkey (1000//24) represents 24 frames per second

# Open camera
cap = cv2.VideoCapture(0) # CAP stands for camera turned on
while 1:
    Read a frame of data from the camera
    ret, frame = cap.read() # frame stores the read data
    cv2.imshow('img',frame)
    key = cv2.waitKey(1000//24)
    if key == ord('q') :break
cap.release()
cv2.destroyAllWindows()

Copy the code

OpenCV camera face recognition

In the Python download pathLib\site-packages\cv2\dataFind the following files

The camera and face recognition codes are as follows

# Camera face recognition

# Use face recognition algorithm provided by OpencV (face recognizer)
face_detector = cv2.CascadeClassifier('./haarcascade_frontalface_alt.xml')

# Open camera
cap = cv2.VideoCapture(0) # CAP stands for camera turned on

while 1:
    Read a frame of data from the camera
    ret, frame = cap.read() # frame stores the read data
    
    # Grayscale processing is performed on the obtained data
    gray = cv2.cvtColor(frame,code=cv2.COLOR_BGR2GRAY)
# cv2.imshow('img',gray)
    # Face recognition in the image after gray processing
    faces = face_detector.detectMultiScale(gray) # Multiple faces identified
    for x,y,w,h in faces:
        cv2.circle(frame,(x+w//2,y+h//2),w//2[0.255.0].2) # Identify faces with circles
    cv2.imshow('frame',frame)
    
    
    key = cv2.waitKey(1000//24)
    if key == ord('q') :break
    # cv2.imwrite('tong.jpg',frame)
cap.release()
cv2.destroyAllWindows()

Copy the code