赞
踩
import cv2 import matplotlib.pyplot as plt import numpy as np def show_img_cv2(rgb,window_name = 'bgr'): cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)#cv2.WINDOW_NORMAL:用户可以改变这个窗口大小 cv2.WINDOW_AUTOSIZE:窗口大小自动适应图片大小,并且不可手动更改 cv2.imshow(window_name,rgb),cv2.waitKey() def get_img_cv2(img_path): bgr = cv2.imread(img_path)#如果读取成功,返回(h,w,c)的bgr图片!!,即使你在目录下看到的是rgb,但它读取过来自动转化为bgr if bgr is None: print('cv2 get ', img_path.split('\\')[-1], ' failed! ',end='') raise Exception('maybe there are something wrong with path!') #return return bgr def save_img_cv2(path,bgr): try: succ = cv2.imwrite(path, bgr)#只能保存 BGR 3通道图像 if succ == False: print('check the path!',end=' '); raise NameError() except Exception: print('save img failed!') def plt_img(img): plt.figure() plt.imshow(img) plt.show()#注意,plt需要的img格式为rgb #plt.savefig('plt_fig.png') path = r'C:\Users\13361\Pictures\Camera Roll\mac.jpg' bgr = get_img_cv2(path)#取出(h,w,3)的数组
show_img_cv2(bgr)
plt_img(bgr)
rgb = cv2.cvtColor(bgr,cv2.COLOR_BGR2RGB)
show_img_cv2(rgb,'rgb')
plt_img(rgb)
save_img_cv2(r'..\data\rgb.png',rgb)
save_img_cv2(r'..\data\bgr.png',bgr)
def get_img_PIL(path): from PIL import Image try: img_obj = Image.open(path)#这是一个Image对象(RGB), 直接对图像进行操作,而不是数组 #img_obj.show() #img = np.asarray(img_obj)#转化为数组 #img_obj = Image.fromarray(np.uint8(img))#从数组转化为Image对象 #img_obj.save('')#保存路径 return img_obj except Exception: print('PIL op failed!') img_obj = get_img_PIL(path) img_obj.show() img = np.asarray(img_obj) img.shape (2124, 2070, 3) img_obj = Image.fromarray(np.uint8(img))#从数组转化为Image对象 <PIL.Image.Image image mode=RGB size=2070x2124 at 0x21A1521F7B8> img_obj.save(path)#保存路径
def subpolt(img_dict,row = 1,column = 3):
plt.figure()
for k,(name,img) in enumerate(img_dict.items()):
subplot = plt.subplot(row, column, k+1)#第三个参数代表第几个图像,从1开始
plt.imshow(img) # 通过for循环逐个显示图像
subplot.set_title(name)
plt.xticks([]) # 去掉x轴的刻度
plt.yticks([]) # 去掉y轴的刻度
plt.show()
img_dict = {'bgr(read from cv2)':bgr,'rgb':rgb, 'Image from PIL':img_obj,}
subpolt(img_dict,row = 1,column = 3)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。