Don't talk much, code first
# -*- coding: utf-8 -*- # @Time : 2019/4/28 13:52 # @Author : ljf import torch from torchvision import transforms from PIL import Image import numpy as np import cv2 # 1.1 tensor2Image Image format for drawing and display tensor1 = torch.randint(0,255,(300,300)) transform1 = transforms.ToPILImage(mode="L") image1 = transform1(np.uint8(tensor1.numpy())) # Image must accept the image format uint8, otherwise an error will be reported print(tensor1.size()) print(image1) # image.show() image1.save("gray.jpg") # 1.2 image2tensor sensor format is convenient to use torch for data enhancement, and it is also the format of model training # Cut first, then switch to sensor. The bottom layer is also implemented by PIL transform2 = transforms.Compose([transforms.RandomCrop([200,200],padding=10),transforms.ToTensor()]) image2 = Image.open("gray.jpg") tensor2 = transform2(image2) print(tensor2.size()) # 2.1 tensor2numpy is also used in 1.1. Numpy format is mainly used for easy conversion of data format, and is also conducive to conversion to opencv format. array1 = tensor1.numpy() print(array1.shape) print(array1.dtype) # 2.2 numpy2tensor 1.2 tensor3 = torch.Tensor(array1) tensor4 = transforms.ToTensor()(array1) print(tensor3.size()) print(tensor4.size()) # A dimension will be added # 3.1 numpy2opencv openc format is convenient for drawing the target box and writing on the picture (Image format can also be realized, not very familiar,,) # opencv reads the data format of numpy cv2.imshow("img",np.uint8(array1)) # cv2.waitKey() # cv2.destroyAllWindows() # 3.2 opencv2numpy array2 = cv2.imread("./gray.jpg") # Here, opencv is used to read three channels, and plt is used to read a single channel.. I haven't understood yet print(array2.shape) print(array2.dtype) # 4.1 opecv2Image image3 = Image.fromarray(array2,mode="RGB") # image3.show() # 4.2 Image2opencv # There are two ways, one is slightly complex, but you can save data shapes array3 = transforms.ToTensor()(image3).numpy() # The Image has its own attributes, but it will disturb the data to be one-dimensional list1 = list(image3.getdata()) print(array3.shape) print(list1)
I went back to school to write my paper for ten days, but I didn't update my blog....
The above four formats are often used in an "image classification" project, such as saving pictures, adding Chinese to pictures and so on. Because these codes are not very common and unskilled, they should be found on the Internet every time. This blog is also convenient for me to search and save if you need.
The following update solves the problem of opecv and MATLAB displaying Chinese, and adds the evaluation matrix to the classification model
Welcome to comment and correct