我使用的是annaconda的环境,自行搜索
 
要先熟悉了numpy之后再学习OpenCV
 
 
newImg = cv.imread('./img/learn2.png' , 0 )   cv.imshow('image' , newImg) cv.waitKey(0 )   cv.destroyAllWindows()   cv.namedWindow('image' , cv.WINDOW_NORMAL)   cv.imshow('image' , newImg) cv.waitKey(0 ) cv.destroyAllWindows() cv.imwrite('./newNewImg.png' , newImg) 
一个小的实现,打开窗口,esc关闭,s保存
import  cv2 as  cvimport  numpy as  npimg1 = cv.imread('./img/learn2.png' ,0 ) cv.imshow('image' ,img1) k = cv.waitKey(0 )  if  k == 27 :     cv.destroyAllWindows() elif  k == ord ('s' ):     cv.imwrite('messigray.png' ,img1)     cv.destroyAllWindows() 
官方这样说,如果你使用的是 64 位机器,你需要修改k = cv.waitKey(0)像这样:k = cv.waitKey(0) & 0xFF
import  cv2 as  cvimport  numpy as  npfrom  matplotlib import  pyplot as  pltimg1 = cv.imread('./img/learn2.png' ,0 ) plt.imshow(img1, cmap = 'gray' , interpolation = 'bicubic' ) plt.xticks([]), plt.yticks([])  plt.show() 
彩色图像 OpenCV 用的 BGR 模式,但是 Matplotlib 显示用的 RGB 模式。因此如果图像用 OpenCV 加载,则 Matplotlib 中彩色图像将无法正常显示。更多细节请看练习。 
 
import  numpy as  npimport  cv2 as  cvcap = cv.VideoCapture(1 )   while (True ):         ret, frame = cap.read()     frame = cv.flip(frame, 1 )            gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)          cv.imshow('frame' ,gray)     if  cv.waitKey(1 ) & 0xFF  == ord ('q' ):         break  cap.release() cv.destroyAllWindows() 
先来理解一下,图像与一般的矩阵或张量有何不同(不考虑图像的格式,元数据等信息)。首先,一张图像有自己的属性,宽,高,通道数。其中宽和高是我们肉眼可见的属性,而通道数则是图像能呈现色彩的属性。我们都知道,光学三原色是红色,绿色和蓝色,这三种颜色的混合可以形成任意的颜色。常见的图像的像素通道也是对应的R,G,B三个通道,在OpenCV中,每个通道的取值为0~255,。(注:还有RGBA,YCrCb,HSV等其他图像通道表示)。即,一般彩色图像读进内存之后是一个h * w * c的矩阵,其中h为图像高(相当于矩阵的行),w为图像宽(相当于矩阵列),c为通道数。
import  cv2 as  cvimport  numpy as  npfrom  matplotlib import  pyplot as  pltimg = cv.imread("./img/learn.png" ) print (img)h, w, c = img.shape print (h, w, c)print (img.size)print (img.dtype)img1 = img[100 , 100 ] print ("img1:" , img1)  ar = np.array([0 , 255 , 255 ], dtype='uint8' ) blue = img[100 , 100 , 0 ] print (blue)  green = img[100 , 100 , 1 ] print (green)  red = img[100 , 100 , 2 ] print (red)  img[100 , 100 ] = [255 , 255 , 255 ] print (img[100 , 100 ])