Python-OpenCV 处理图像(一):基本操作 cv2
0x00. 圖片讀、寫(xiě)和顯示操作
安裝好 OpenCV 之后,首先嘗試加載一張最簡(jiǎn)單的圖片并顯示出來(lái),代碼示例:
第一種方式使用cv2.cv的LoadImage、ShowImage和SaveImage函數(shù)
import cv2.cv as cv# 讀圖片 image=cv.LoadImage('img/image.png', cv.CV_LOAD_IMAGE_COLOR)#Load the image #Or just: image=cv.LoadImage('img/image.png')cv.NamedWindow('a_window', cv.CV_WINDOW_AUTOSIZE) #Facultative cv.ShowImage('a_window', image) #Show the image# 寫(xiě)圖片 cv.SaveImage("thumb.png", thumb) cv.WaitKey(0) #Wait for user input and quit也可以直接使用cv2的imread、imwrite和imshow函數(shù)
import numpy as np import cv2img = cv2.imread('messi5.jpg',0) cv2.imshow('image',img) k = cv2.waitKey(0) if k == 27: # wait for ESC key to exitcv2.destroyAllWindows() elif k == ord('s'): # wait for 's' key to save and exitcv2.imwrite('messigray.png',img)cv2.destroyAllWindows()imread函數(shù)還可以定義加載的mode,默認(rèn)是以RGB模式處理圖片:
import cv2 grayImage = cv2.imread('MyPic.png', cv2.CV_LOAD_IMAGE_GRAYSCALE) # 可選參數(shù)CV_LOAD_IMAGE_COLOR (BGR), CV_LOAD_IMAGE_GRAYSCALE (grayscale), CV_LOAD_IMAGE_UNCHANGED(neither) cv2.imwrite('MyPicGray.png', grayImage)0x01. 獲取圖片屬性
import cv2 img = cv2.imread('img/image.png') print img.shape # (640, 640, 3) print img.size # 1228800 print img.dtype # uint8 # 在debug的時(shí)候,dtype很重要0x02. 輸出文本
在處理圖片的時(shí)候,我們經(jīng)常會(huì)需要把一些信息直接以文字的形式輸出在圖片上,下面的代碼將實(shí)現(xiàn)這個(gè)效果:
import cv2.cv as cvimage=cv.LoadImage('img/lena.jpg', cv.CV_LOAD_IMAGE_COLOR) #Load the imagefont = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8) #Creates a fonty = image.height / 2 # y position of the text x = image.width / 4 # x position of the textcv.PutText(image,"Hello World !", (x,y),font, cv.RGB(255, 255, 255)) #Draw the textcv.ShowImage('Hello World', image) #Show the imagecv.WaitKey(0)cv2:
cv2.putText(frame, 'Hello World', (300,100), 0, 0.5, (0,0,255),2)0x03. 縮放圖片
下面的例子將實(shí)現(xiàn)縮放圖片并保存,這個(gè)在使用 OpenCV 做圖像處理的時(shí)候都是很常用的操作:
import cv2.cv as cvim = cv.LoadImage("img/alkaline.jpg") #get the imagethumb = cv.CreateImage((im.width / 2, im.height / 2), 8, 3) #Create an image that is twice smaller than the originalcv.Resize(im, thumb) #resize the original image into thumb #cv.PyrDown(im, thumb)cv.SaveImage("thumb.png", thumb) # save the thumb imagecv2:
import cv2 import numpy as np img = cv2.imread('messi5.jpg') res = cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)#ORheight, width = img.shape[:2] res = cv2.resize(img,(2*width, 2*height), interpolation = cv2.INTER_CUBIC)0x04. 圖像平移
import cv2 import numpy as npimg = cv2.imread('messi5.jpg',0) rows,cols = img.shapeM = np.float32([[1,0,100],[0,1,50]]) dst = cv2.warpAffine(img,M,(cols,rows))cv2.imshow('img',dst) cv2.waitKey(0) cv2.destroyAllWindows()0x05. 圖像旋轉(zhuǎn)
img = cv2.imread('messi5.jpg',0) rows,cols = img.shapeM = cv2.getRotationMatrix2D((cols/2,rows/2),90,1) dst = cv2.warpAffine(img,M,(cols,rows))0x06. 仿射變換
import cv2 import numpy as npimg = cv2.imread('mao.jpg') rows,cols,ch = img.shapepts1 = np.float32([[50,50],[200,50],[50,200]]) pts2 = np.float32([[10,100],[200,50],[100,250]])M = cv2.getAffineTransform(pts1,pts2)dst = cv2.warpAffine(img,M,(cols,rows))cv2.imshow('image',dst) cv2.waitKey(0)0x07. 圖像顏色變換
實(shí)際使用過(guò)程中,我們經(jīng)常也需要對(duì)一些圖片的顏色空間做一些改變之類的:
c2.cv:
import cv2.cv as cv im=cv.LoadImage('img/fruits.jpg',cv.CV_LOAD_IMAGE_COLOR) res = cv.CreateImage(cv.GetSize(im), cv.CV_8UC2, 3) #cv.CV_32F, cv.IPL_DEPTH_16S, ... cv.Convert(im, res) cv.ShowImage("Converted",res) res2 = cv.CreateImage(cv.GetSize(im), cv.CV_8UC2, 3) cv.CvtColor(im, res2, cv.CV_RGB2BGR) # HLS, HSV, YCrCb, .... cv.ShowImage("CvtColor", res2) cv.WaitKey(0)-
cv.Convert():將圖片從一個(gè)顏色空間轉(zhuǎn)到另一個(gè)顏色空間
-
cv.CvtColor(src, dst, code):
cv2:
cv2.cvtColor(input_image, flag)函數(shù)實(shí)現(xiàn)圖片顏色空間的轉(zhuǎn)換,flag 參數(shù)決定變換類型。如 BGR->Gray flag 就可以設(shè)置為 cv2.COLOR_BGR2GRAY 。
一個(gè)簡(jiǎn)單的例子,下面的代碼實(shí)現(xiàn)識(shí)別攝像視頻中藍(lán)色的部分:
import cv2 import numpy as npcap = cv2.VideoCapture(0)while(1):# 讀取視頻的每一幀_, frame = cap.read()# 將圖片從 BGR 空間轉(zhuǎn)換到 HSV 空間hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)# 定義在HSV空間中藍(lán)色的范圍lower_blue = np.array([110,50,50])upper_blue = np.array([130,255,255])# 根據(jù)以上定義的藍(lán)色的閾值得到藍(lán)色的部分mask = cv2.inRange(hsv, lower_blue, upper_blue)res = cv2.bitwise_and(frame,frame, mask= mask)cv2.imshow('frame',frame)cv2.imshow('mask',mask)cv2.imshow('res',res)k = cv2.waitKey(5) & 0xFFif k == 27:breakcv2.destroyAllWindows()以上的代碼給出了視頻中獲取興趣對(duì)象的基本思想。
0x08. 通道的拆分/合并處理
對(duì)于一張圖片的 R、G、B 通道,我們可以很方便的使用 OpenCV 獲取并分離或者合并:
(這是將圖像灰度化處理的一種方式)
cv2.cv
import cv2.cv as cvorig = cv.LoadImage('img/fruits.jpg') b = cv.CreateImage(cv.GetSize(orig), orig.depth, 1) g = cv.CloneImage(b) r = cv.CloneImage(b) cv.Split(orig, b, g, r, None)merged = cv.CreateImage(cv.GetSize(orig), 8, 3) cv.Merge(g, b, r, None, merged)cv.ShowImage("Image", orig) cv.ShowImage("Blue", b) cv.ShowImage("Green", g) cv.ShowImage("Red", r) cv.ShowImage("Merged", merged)cv.WaitKey(0)cv2
import cv2 img = cv2.imread('img/image.png') b,g,r = cv2.split(img) img = cv2.merge((b,g,r))0x09. 圖片添加邊距
cv2.copyMakeBorder函數(shù)
import cv2 import numpy as npBLUE = [255,0,0]img1 = cv2.imread('opencv_logo.png')replicate = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REPLICATE) reflect = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT) reflect101 = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT_101) wrap = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_WRAP) constant= cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)總結(jié)
以上是生活随笔為你收集整理的Python-OpenCV 处理图像(一):基本操作 cv2的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 游戏行业搜索实践
- 下一篇: PyFlink 开发环境利器:Zeppe