'''
PIL.Image, numpy, tensor, cv2 之间的互转
'''
import cv2
import torch
from PIL import Image
import numpy as np
from torchvision import transforms
img_path='catdog.jpg'
img_PIL = Image.open(img_path).convert('RGB') # plt读取的是单通道
print(type(img_PIL)) #
# im.show()
'''
PIL.Image --> numpy
'''
img_numpy = np.array(img_PIL)
print(type(img_numpy)) #
'''
numpy --> PIL.Image
'''
# img = img[:,:,0] #第1通道
img_PIL=Image.fromarray(img_numpy)
print(type(img_PIL)) #
'''
PIL.Image --> tensor
'''
transform = transforms.Compose([transforms.ToTensor()])
img_tensor = transform(img_PIL)
print(type(img_tensor)) #
'''
tensor --> PIL.Image
'''
img_PIL = transforms.ToPILImage()(img_tensor).convert('RGB')
print(type(img_PIL)) #
'''
tensor --> numpy
'''
img_numpy = img_tensor.numpy()
print(type(img_numpy)) #
'''
numpy --> tensor
'''
img_tensor = torch.from_numpy(img_numpy)
print(type(img_tensor)) #
'''
cv2(numpy) --> tensor
'''
# opencv读取出来就是numpy形式的,并且是三通道
# 因此opencv与PIL.Image, tensor的格式转换和numpy与PIL.Image, tensor的格式转换一样
img_cv = cv2.imread(img_path)
print(type(img_cv)) #
img_tensor = torch.from_numpy(img_cv)
print(type(img_tensor)) #
'''
cv2(numpy) --> PIL.Image
'''
img_PIL = Image.fromarray(img_cv,mode="RGB")
print(type(img_PIL)) #
# 下面cv2在图像上画线转载自:https://www.cnblogs.com/sunnyCx/p/8136275.html
img=cv2.imread(img_path)
# 给图片画线
# 参数分别表示,起始和终止点的坐标,线的颜色,最后一个参数可以不填,代表线的粗细
# 线的颜色使用BGR表示,越大代表成分越多,红(0,0,255),白(255,255,255)
cv2.line(img, (0, 0), (150, 150), (0, 0, 255), 10)
# 给图片画矩形
# 参数分别表示,左上和右下点的坐标,颜色,粗细
cv2.rectangle(img, (15, 25), (200, 100), (0, 255, 0), 2)
# 圆形,指定中心点和半径 -1表示填充,默认不填充
cv2.circle(img, (100, 63), 55, (255, 0, 0), -1)
# 多边形,指定一个数组代表各个点
# True代表第一个点和最后一个点是否连线
pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)
cv2.polylines(img, [pts], True, (0, 0, 255))
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()