import cv2 import numpy as np import glob ''' img = cv2.imread('figures/img_1.jpg') cv2.imshow('src', img) print(img.shape) #(h,w,c) 打印图片的维度,(高度,宽度,通道数) print(img.size) #像素总数目 print(img.dtype) #unit8 print(img) #显示一个numpy矩阵 cv2.waitKey() #图片显示着,直到按下任意一个键才被关掉 gray = cv2.imread('figures/img_1.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow('gray',gray) cv2.waitKey() anyColor = cv2.imread('figures/img_1.jpg', cv2.IMREAD_ANYCOLOR) cv2.imshow('anyColor',anyColor) cv2.waitKey() Color = cv2.imread('figures/img_1.jpg', cv2.IMREAD_COLOR) cv2.imshow('Color',Color) cv2.waitKey() #也可以先读入彩色图,在转换为灰色图 color_1 = cv2.imread('figures/img_1.jpg') gray_1 = cv2.cvtColor(color_1, cv2.COLOR_BGR2GRAY) cv2.imshow('gray_1', gray_1) cv2.waitKey() #读到图片不存在时,加入判断语句,如果为空,做异常处理 img_2 = cv2.imread('figures/img_2.jpg') if img_2 == None: print('Fail to load image!') ''' ''' #图片的矩阵变换 #做卷积的时候,需要对不同通道应用卷积,这时:(height,width,channel)---> (channel,height,width) img = cv2.imread('figures/img_1.jpg') cv2.imshow('img', img) print(img.shape) cv2.waitKey() img_1 = img.transpose(2, 0, 1) #cv2.imshow('img_1', img_1) #转换之后不能再显示,执行会出错 print(img_1.shape) #cv2.waitKey() #扩展维度,例如--->(batch_size, channels, height, width) #预测单张图片,加一列作为图片的个数 img_2 = np.expand_dims(img, axis=0) print(img_2.shape) #(1, 480, 854, 3) #训练阶段构建patch---> (batch_size, channels, height, width) data_list = [] images = glob.glob('D:/PycharmProjects/image2video/blackswan/*.png') for imageName in images: im = cv2.imread(imageName) data_list.append(im) data_arr = np.array(data_list) print(data_arr.shape) #(50, 480, 854, 3) ''' ''' #图片归一化 #opencv读入的图片矩阵数值是0-255,有时我们需要对其进行归一化处理 img = cv2.imread('figures/img_1.jpg') print(img.dtype) #unit8 print(img) img_1 = img.astype("float") / 255.0 #img为unit8,需要先转换为float型 print(img_1.dtype) #float64 print(img_1) # 存储图片 cv2.imwrite('img_2.jpg', img_1) img_3 = img_1 * 255 #要得到可视化的图片,需要乘以255还原 cv2.imwrite('img_3.jpg', img_3) # BGR---->RGB,opencv读入的图片通道排列是BGR,而不是RGB img_4 = cv2.imread('figures/img_1.jpg') img_4 = cv2.cvtColor(img_4, cv2.COLOR_BGR2RGB) #访问像素 gray = cv2.cvtColor(img_4, cv2.COLOR_BGR2GRAY) print(img_4[10,10]) #3channels print(gray[10, 10]) #1channel img_4[10, 10] = [255, 255, 255] #修改像素值 gray[10,10] = 255 print(img_4[10,10]) #----->[255,255,255] print(gray[10,10]) #----->255 #ROI操作(提取感兴趣的区域) roi = img_4[200:550,100:450,:] cv2.imshow('roi',roi) cv2.waitKey() ''' #通道操作 #分离通道 img_5 = cv2.imread('figures/img_1.jpg') b, g, r = cv2.split(img_5) print(b) #[[]] print(img_5) #[[[]]] #合并通道 img_6 = cv2.merge((b, g, r)) print(img_6) img_5[:, :, 2] = 0 print(img_5) cv2.imshow('img5', img_5) cv2.waitKey()