栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

PIL.Image, numpy, tensor, cv2 之间的互转,以及在cv2在图片上画各种形状的线

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PIL.Image, numpy, tensor, cv2 之间的互转,以及在cv2在图片上画各种形状的线

'''
 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()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/444283.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号