opencv
opencv是計算機視覺中最受歡迎的庫,最初由intel使用c和c ++進行開發的,現在也可以在python中使用。該庫是一個跨平臺的開源庫,是免費使用的。opencv庫是一個高度優化的庫,主要關注實時應用程序。
opencv庫是2500多種優化算法的組合,可用于檢測和識別不同的人臉,實時識別圖像中的對象,使用視頻和網絡攝像頭對不同的人類動作進行分類,跟蹤攝像機的運動,跟蹤運動對象(例如汽車,人等),實時計數對象,縫合圖像來產生高分辨率圖像,從圖像數據庫中查找相似的圖像,從使用閃光燈拍攝的圖像中消除紅眼并提高圖像質量,跟蹤眼睛的運動,跟蹤臉部等。
它擁有大約4.7萬活躍用戶社區,下載量超過1800萬。谷歌,亞馬遜,特斯拉,微軟,本田等許多大公司都使用open cv來改善他們的產品,它更是驅動了ai的發展。
先決條件
在開始編寫代碼之前,我們需要在設備上安裝opencv。
如果你是proin編程專家,并且熟悉每個ide,那么請使用pycharm并從設置中的程序包管理器安裝opencv-python。
如果你是初學者或中級程序員,或者只是想關注博客,那么我們將使用代碼編輯器而不是ide。
只需轉到visual studio code網站并根據你的操作系統下載最新版本即可。
- https://code.visualstudio.com/download
現在,我們將創建一個虛擬環境,并在其中安裝opencv。打開終端,然后使用cd定位到桌面,使用mkdir 創建一個名為opencv
的文件夾,然后運行以下命令。
1
|
python - m venv env |
現在,使用env\scripts\activate
激活環境,你會在c:\users\username\desktop\opencv
之前看到小括號(env)出現。
現在,只需使用pip安裝opencv。
我們會在本文中涵蓋7個主題
1. 讀,寫和顯示圖像
2. 讀取視頻并與網絡攝像頭集成
3. 調整大小和裁剪圖像
4. 基本的圖像過濾器使用的函數
5. 繪制不同的形狀
6. 在圖像上書寫文字
7. 檢測并裁剪臉部
讀,寫和顯示圖像
要使用opencv讀取圖像,我們有imread()函數; 要顯示圖像,有imshow()函數,而對于書寫,我們有imwrite()函數。讓我們看看它們的語法。
imread():
1
2
3
|
img = cv2.imread( "path_to_image.jpg/png" ) example img = imread( "images/dog0.jpg" ) |
imshow():
1
2
3
|
cv2.imshow( "window name" ,img_var) example imshow( "dog image" ,img) |
imwrite():
1
2
3
4
5
|
cv2.imwrite(filename, image) filename: a string representing the file name. the filename must include image format like .jpg, .png, etc. image: it is the image that is to be saved. example cv2.imwrite( 'images/img' ,img) |
讀取視頻并與網絡攝像頭集成
讀取視頻文件與在opencv中讀取圖像文件非常相似,區別在于我們使用了cv2.videocapture。
句法
1
2
3
|
video = cv2.videocapture( "filepath.mp4" ) example video = cv2.videocapture( "video/dog/dog.mp4" ) |
視頻是許多幀結合在一起的集合,每幀都是一幅圖像。要使用opencv觀看視頻,我們只需要使用while循環顯示視頻的每一幀。
1
2
3
4
5
|
while true: success , img = cap.read() cv2.imshow( "video" ,img) if cv2.waitkey( 1 ) & 0xff = = ord ( 'q' ): ##key 'q' will break the loop break |
要與網絡攝像頭集成,我們需要傳遞網絡攝像頭的端口值而不是視頻路徑。如果你使用的是筆記本電腦,但沒有連接任何外部網絡攝像頭,則只需傳遞參數0;如果你有外部網絡攝像頭,則傳遞參數1。
1
2
3
4
5
6
7
8
9
|
cap = cv2.videocapture( 0 ) cap. set ( 3 , 640 ) ## frame width cap. set ( 4 , 480 ) ## frame height cap. set ( 10 , 100 ) ## brightness while true: success, img = cap.read() cv2.imshow( "video" ,img) if cv2.waitkey( 1 ) & 0xff = = ord ( 'q' ): break |
調整大小和裁剪圖像
調整大小是更改圖像形狀的過程。在opencv中,我們可以使用resize函數調整圖像形狀的大小。
句法
1
2
3
4
5
6
|
cv2.resize(img,(width,height)) img: image which we want to resize width: new width of the resize image height: new height of the resize image example cv2.resize(img,( 224 , 224 )) |
要首先調整圖像的大小,我們需要知道圖像的形狀。我們可以使用shape來找到任何圖像的形狀,然后根據圖像形狀,可以增加或減小圖像的大小。讓我們看看示例。
1
2
3
4
5
6
7
8
9
10
|
import cv2 img = cv2.imread( "images/img0.jpg" ) ##choose any image print (img.shape) imgresize = cv2.resize(img,( 224 , 224 )) ##decrease size imgresize2 = cv2.resize(img,( 1024 , 1024 )) ##increase size cv2.imshow( "image" ,img) cv2.imshow( "image resize" ,imgresize) cv2.imshow( "image increase size" ,imgresize2) print (imgresize.shape) cv2.waitkey( 0 ) |
如果你不想對寬度和高度進行硬編碼,也可以使用形狀,然后使用索引來增加寬度和高度。
1
2
3
4
5
6
7
8
9
10
11
|
import cv2 img = cv2.imread( "images/img0.jpg" ) ##choose any image print (img.shape) shape = img.shape imgresize = cv2.resize(img,(shape[ 0 ] / / 2 ,shape[ 1 ] / / 2 )) ##decrease size imgresize2 = cv2.resize(img,(shape[ 0 ] * 2 ,shape[ 1 ] * 2 )) ##increase size cv2.imshow( "image" ,img) cv2.imshow( "image resize" ,imgresize) cv2.imshow( "image increase size" ,imgresize2) print (imgresize.shape) cv2.waitkey( 0 ) |
裁剪圖像
裁剪是獲取圖像的一部分過程。在opencv中,我們可以通過定義裁剪后的矩形坐標來執行裁剪。
句法
1
2
3
4
5
|
imgcropped = img[y1:y2, x1:x2] (x1,y1): top - left vertex (x2,y2): bottom - right vertex example imgcropped = img[ 0 : 100 , 200 : 200 ] |
使用裁剪方法,讓我們嘗試從圖像中獲取蒙娜麗莎的臉。
1
2
3
4
5
6
|
import cv2 img = cv2.imread( "images/img0.jpg" ) imgcropped = img[ 50 : 250 , 120 : 330 ] cv2.imshow( "image cropped" ,imgcropped) cv2.imshow( "image" ,img) cv2.waitkey( 0 ) |
你也可以使用paint來找到(x1,y1),(x2,y2)的正確坐標。
右鍵單擊圖像并保存,嘗試從圖像中獲取王卡。
提示:使用paint來找到正確的坐標,最后使用調整大小來增加裁剪圖像的大小。
“在尋求解決方案之前,請嘗試自己動手做。”
解決方案- https://gist.github.com/abhayparashar31/9b01473431de765c0a73e81271233d91
基本的圖像過濾器使用的函數
我們可以在圖像上使用許多基本的濾鏡操作,例如將圖像轉換為灰度圖像,模糊圖像等等。讓我們一一看一下比較重要的操作。
將圖像轉為灰度圖像
要將圖像轉換為灰度,我們可以使用一個函數cvtcolor,這里我們將cv2.color_bgr2gray作為參數傳遞。
1
2
3
4
5
|
imggray = cv2.cvtcolor(img,cv2.code) img: original image code: conversion code for gray(color_bgr2gray) example imggray = cv2.cvtcolor(img,cv2.color_bgr2gray) |
將圖像轉為hsv
要將圖像轉換為hsv,我們可以使用函數cvtcolor,這里我們將cv2.color_bgr2hsv作為參數傳遞。它主要用于對象跟蹤。
1
2
3
4
5
|
imggray = cv2.cvtcolor(img,cv2.code) img: original image code: conversion code for gray(color_bgr2hsv) example imghsv = cv2.cvtcolor(img,cv2.color_bgr2hsv) |
圖像模糊
模糊用于去除圖像中的多余噪聲,也稱為平滑,這是對圖像應用低通濾波器的過程。要在opencv中使用模糊,我們有一個函數gaussianblur。
1
2
3
4
5
6
|
imgblur = cv2.gaussianblur(img,(sigmax,sigmay),kernalsize) kernalsize − a size object representing the size of the kernel. sigmax − a variable representing the gaussian kernel standard deviation in x direction. sigmay - same as sigmax exmaple imgblur = cv2.gaussianblur(img,( 3 , 3 ), 0 ) |
邊緣檢測
在opencv中,我們使用canny邊緣檢測器來檢測圖像中的邊緣,也有不同的邊緣檢測器,但最著名的是canny邊緣檢測器。canny邊緣檢測器是一種邊緣檢測算子,它使用多階段算法來檢測圖像中的大范圍邊緣,它由john f. canny在1986年開發。
1
2
3
4
|
imgcanny = cv2.canny(img,threshold1,threshold2) threshold1,threshold2:different values of threshold different for every images example imgcanny = cv2.canny(img, 100 , 150 ) |
膨脹
膨脹是用來增加圖像中邊緣的大小。首先,我們定義一個大小為奇數(5,5)的核矩陣,然后利用核函數對圖像進行放大。我們對canny邊緣檢測器的輸出圖像進行了放大處理。
1
2
|
kernel = np.ones(( 5 , 5 ),np.uint8) ## defining kernel of 5x5 imgdialation = cv2.dilate(imgcanny,kernel,iterations = 1 ) ##dialation |
腐蝕
腐蝕是擴張的反面,它用于減小圖像邊緣的尺寸。首先,我們定義一個奇數(5,5)的核矩陣大小,然后使用核對圖像執行腐蝕。我們對canny邊緣檢測器的輸出圖像施加腐蝕。
1
2
|
kernel = np.ones(( 5 , 5 ),np.uint8) ## defining kernel of 5x5 imgdialation = cv2.erode(imgcanny,kernel,iterations = 1 ) ##erosion |
現在,在同一程序中將所有基礎函數應用于monalisa映像。
繪制不同的形狀
我們可以使用opencv來繪制矩形,圓形,直線等不同的形狀。
矩形:
要在圖像上繪制矩形,我們使用矩形函數。在函數中,我們傳遞寬度,高度,x,y,rgb中的顏色,厚度作為參數。
1
2
3
4
5
6
7
8
9
|
cv2.rectangle(img,(w,h),(x,y),(r,g,b),thickness) w: width h: height x: distance from x axis y: distance from y axis r,g,b: color in rgb form ( 255 , 255 , 0 ) thickness: thickness of rectangel(integer) example cv2.rectangle(img,( 100 , 300 ),( 200 , 300 ),( 255 , 0 , 255 ), 2 ) |
圓:
要繪制一個圓,我們使用cv2.circle。我們傳遞x,y,半徑大小,rgb形式的顏色,厚度作為參數。
1
2
3
4
5
6
7
8
|
cv2.circle(img,(x,y),radius,(r,g,b),thickness) x: distance from x axis y: distance from y axis radius: size of radius(integer) r,g,b: color in rgb form ( 255 , 255 , 0 ) thickness: thickness of rectangel(integer) example cv2.circle(img,( 200 , 130 ), 90 ,( 255 , 255 , 0 ), 2 ) |
線:
要繪制一條線,我們使用cv2.line,使用起點(x1,y1),終點(x2,y2),rgb形式的顏色,厚度作為參數。
1
2
3
4
5
6
7
|
cv2.line(img,(x1,y1),(x2,y2),(r,g,b),thickness) x1,y1: start point of line (integer) x2,y2: end point of line (integer) r,g,b: color in rgb form ( 255 , 255 , 0 ) thickness: thickness of rectangel(integer) example cv2.line(img,( 110 , 260 ),( 300 , 260 ),( 0 , 255 , 0 ), 3 ) |
在圖像上書寫文字
在opencv中,我們有一個函數cv2.puttext, 可以在特定位置的圖像上寫文本。它以圖像,文本,x,y,顏色,字體,字體比例,粗細為輸入。
1
2
3
4
5
6
7
8
9
10
11
|
cv2.puttext(img,text,(x,y),font,font_scale,(r,g,b),thickness) img: image to put text on text: text to put on image x: text distance from x axis y: text distance from y axis font: type of font ( all font types) font_scale: scale of font(integer) r,g,b: color in rgb form ( 255 , 255 , 0 ) thickness: thickness of rectangel(integer) example cv2.puttext(img, "hello" ,( 120 , 250 ),cv2.font_hershey_complex, 1 ,( 255 , 255 , 255 ), 2 ) |
下載monalisa圖片。
任務:使用形狀和文本為左側圖像中所示的monalisa臉創建框架。
提示:首先是一個圓形,然后是矩形,然后根據圓形和矩形放置文本,最后根據文本放置一行。
解決方案- https://gist.github.com/abhayparashar31/af36bf25ce61345266db4b54aba33be1
檢測并裁剪臉部
在創建人臉識別系統時,人臉檢測是非常有用的。在opencv中,我們提供了許多可用于不同目的的預訓練haar級聯分類器。在opencv github上查看分類器的完整列表。
- https://github.com/opencv/opencv/tree/master/data/haarcascades
為了檢測opencv中的人臉,我們使用了haarcascade_frontalface_default.xml分類器,它會返回我們圖像的四個坐標(w,h,x,y),使用這些坐標,我們將在臉部上繪制一個矩形,然后使用相同的坐標來裁剪臉部。現在使用imwrite,我們將裁剪的圖像保存在目錄中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import cv2 # load the cascade face_cascade = cv2.cascadeclassifier( 'haarcascade_frontalface_default.xml' ) # read the input image img = cv2.imread( 'images/img0.jpg' ) # convert into grayscale gray = cv2.cvtcolor(img, cv2.color_bgr2gray) # detect faces faces = face_cascade.detectmultiscale(gray, 1.3 , 4 ) # draw rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), ( 255 , 0 , 0 ), 2 ) # cropping face crop_face = img[y:y + h, x:x + w] #saving cropped face cv2.imwrite( str (w) + str (h) + '_faces.jpg' , crop_face) cv2.imshow( 'img' , img) cv2.imshow( "imgcropped" ,crop_face) cv2.waitkey() |
參考文獻
[1] https://opencv.org/about/
[2] https://pypi.org/project/opencv-python/
[3] https://www.murtazahassan.com/
以上就是python opencv快速入門教程的詳細內容,更多關于python opencv入門教程的資料請關注服務器之家其它相關文章!
原文鏈接:https://mp.weixin.qq.com/s/6ZH6QXS2VaUrTKIOimiSHA