0x00. 图片读、写和显示操作
安装好 OpenCV 之后,首先尝试加载一张最简单的图片并显示出来,代码示例:
第一种方式使用cv2.cv的LoadImage
、ShowImage
和SaveImage
函数
1 2 3 4 5 6 7 8 9 10 11 12 |
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 # 写图片 cv.SaveImage("thumb.png", thumb) cv.WaitKey(0) #Wait for user input and quit |
也可以直接使用cv2的imread
、imwrite
和imshow
函数
1 2 3 4 5 6 7 8 9 10 11 |
import numpy as np import cv2 img = cv2.imread('messi5.jpg',0) cv2.imshow('image',img) k = cv2.waitKey(0) if k == 27: # wait for ESC key to exit cv2.destroyAllWindows() elif k == ord('s'): # wait for 's' key to save and exit cv2.imwrite('messigray.png',img) cv2.destroyAllWindows() |
imread
函数还可以定义加载的mode,默认是以RGB模式处理图片:
1 2 3 4 |
import cv2 grayImage = cv2.imread('MyPic.png', cv2.CV_LOAD_IMAGE_GRAYSCALE) # 可选参数CV_LOAD_IMAGE_COLOR (BGR), CV_LOAD_IMAGE_GRAYSCALE (grayscale), CV_LOAD_IMAGE_UNCHANGED(neither) cv2.imwrite('MyPicGray.png', grayImage) |
0x01. 获取图片属性
1 2 3 4 5 6 7 8 9 |
import cv2 img = cv2.imread('img/image.png') print img.shape # (640, 640, 3) print img.size # 1228800 print img.dtype # uint8 # 在debug的时候,dtype很重要 |
0x02. 输出文本
在处理图片的时候,我们经常会需要把一些信息直接以文字的形式输出在图片上,下面的代码将实现这个效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import cv2.cv as cv image=cv.LoadImage('img/lena.jpg', cv.CV_LOAD_IMAGE_COLOR) #Load the image font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8) #Creates a font y = image.height / 2 # y position of the text x = image.width / 4 # x position of the text cv.PutText(image,"Hello World !", (x,y),font, cv.RGB(255, 255, 255)) #Draw the text cv.ShowImage('Hello World', image) #Show the image cv.WaitKey(0) |
cv.WaitKey(0)