opencv读取图像并显示
1. import cv2 2. from PIL import Image 3. 4. img = cv2.imread('dog.jpg') # 用opencv读取图像 5. cv2.imshow("img",img) 6. cv2.waitKey(0)
opencv转Image
import cv2 from PIL import Image img = cv2.imread("dog.jpg") ''' 因为opencv读取图像为BGR,在Image是RGB,所以要进行通道转换 ''' img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) img = Image.fromarray(img) img.show()
Image读取和显示图像
from PIL import Image img = Image.open("dog.jpg") img.show()
Image转numpy
from PIL import Image import numpy as np import matplotlib.pyplot as plt img = Image.open("dog.jpg") img = np.array(img) plt.title("img") plt.imshow(img) plt.show()
Image转opencv
import cv2 from PIL import Image import numpy as np img = Image.open("dog.jpg") img = cv2.cvtColor(np.array(img), cv2.COLO_RGB2BGR) cv2.imshow(img) cv2.waitKey(0)
将上述代码进行了一个整合,可以直接在终端以命令方式进行图片的显示
如你想用opencv读取图像并显示,终端输入以下命令
python test.py --mode cv2 --image "dog.jpg"
例如你想用opencv读取图像,用Image进行显示,可以输入以下命令:
python test.py --mode cv2 --image "dog.jpg" --cv2Image
如果你想用Image读取图像并显示,终端输入以下命令
python test.py --mode Image --image "dog.jpg"
如果你想用Image读取图像用plt.show显示,终端输入以下命令:
python test.py --mode Image --image "dog.jpg" --PIL2numpy
如果你想用Image读取图像并用opencv显示,终端输入以下命令:
python test.py --mode Image --image "dog.jpg" --PIL2cv
import cv2 import numpy as np import matplotlib.pyplot as plt from PIL import Image import argparse def CV_image(opt): print("图像路径:", opt.image) img = cv2.imread(opt.image) if img is None: print("打开图像失败") if not opt.cv2Image: cv2.imshow("image", img) cv2.waitKey(0) if opt.cv2Image: ''' 因为cv读取的图像是BGR格式,Image显示需要RGB,所以要转换一下 ''' img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = Image.fromarray(img) img.show(title='img') def Image_image(opt): img = Image.open(opt.image) if opt.PIL2numpy: img = np.array(img) plt.title("img") plt.axis('off') # 可以关闭坐标系 plt.imshow(img) plt.show() elif opt.PIL2cv: img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) cv2.imshow("img", img) cv2.waitKey(0) else: img.show(title='image') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--mode', type=str, default='cv2', help='read image mode,you can choose cv2 or Image') parser.add_argument('--image', type=str, default=' ', help='image path') parser.add_argument('--PIL2numpy', action='store_true', default=False, help='PIL2numpy') parser.add_argument('--cv2Image', action='store_true', default=False, help='opencv 2 Image show ') parser.add_argument('--PIL2cv', action='store_true', default=False, help='Image 2 opencv show') opt = parser.parse_args() if opt.mode == 'cv2': CV_image(opt) if opt.mode == 'Image': Image_image(opt)