注意:pytorch中对图像预处理是transforms的输入必须是PIL格式的文件,使用cv2读取的图片就按照第二条的代码处理(3通道合并、归一化处理)
from PIL import Image
img = Image.open("test1.jpg")读取图像
img.show()展示图片
print(img.size)查看图像是255*255大小的数据,每个像素点是0-1的值。而cv2读出每个像素点为0-255.
如果进行FasterRCNN推理:
net=torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485,0.456,0.406],
std=[0.229,0.224,0.225])])
img = Image.open("test1.jpg")
img_t = transform(img)#裁剪及转换为张量
batch_t = torch.unsqueeze(img_t,0)
net.eval()
out2=net(batch_t)
src_img=cv2.imread("test1.jpg")#读取图片
cv2.imshow("result",src_img)#显示图片
print(src_img.shape)#可查看大小为(255,255,3)此时cv2读取的图像格式为BGR,且每个像素点的值为0-255,需要使用 cv2.cvtColor(img,cv2.COLOR_BGR2RGB)转换为RGB格式
import cv2
import torch
import torchvision
import numpy as np
from PIL import Image
import PIL
from matplotlib import pyplot as plt
from torchvision import transforms
net=torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
net.eval()
src_img=cv2.imread("test1.jpg")
img = cv2.cvtColor(src_img,cv2.COLOR_BGR2RGB)
img_tensor = torch.from_numpy(img/255.).permute(2,0,1).float()
input=[]
input.append(img_tensor)
out2=net(input)
boxes=out2[0]['boxes']
labels=out2[0]['labels']
scores=out2[0]['scores']
boxes=boxes.detach().numpy()
boxes=np.array(boxes,np.uint8)
for idx in range(boxes.shape[0]):
if scores[idx] >= 0.95:
x1,y1,x2,y2=boxes[idx][0],boxes[idx][1],boxes[idx][2],boxes[idx][3]
cv2.rectangle(src_img,(x1,y1),(x2,y2),(0,255,0),thickness=2)
cv2.imshow("result",src_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img_pil=Image.fromarray(cv2.cvtColor(img_cv,cv2.COLOR_BGR2RGB))
img_cv=cv2.cvtColor(np.asarray(img_pil),cv2.COLOR_RGB2BGR)
Image读取的图片使用cv2显示:
img = Image.open("test1.jpg")
print(img.size)#(255,255)
cv2img=np.array(img.convert('RGB'))#转换为RGB格式
print(cv2img.shape)#(255,255,3)
cv2img=cv2.cvtColor(cv2img, cv2.COLOR_RGB2BGR)#cv2需要BGR格式图片
cv2.imshow("result",cv2img)#可正常展示
从txt文件加载字符串保存为json格式:
coco_classes.json:
代码:
import json
coco_class_path="./coco_classes.txt"#txt文件每行为一个数据如: 1 person前面为字典关键字key,person为字典value
jsondata={}#json文件是字典结构,用于存放数据
with open(coco_class_path,'r') as coco:
for line in coco.readlines():#遍历txt文件每行字符串
line=line.strip().split()#strip()去除两边控空字符,split()以空格分割字符串
if len(line)>2:
print(line[0],line[1],line[2])
jsondata[line[0]] = line[1]+' '+line[2]#有些value为两个单词
else:
jsondata[line[0]] = line[1]
with open('coco_classes.json','w') as coco:#写入json文件
json.dump(jsondata,coco)
with open('coco_classes.json','r') as coco:#从json文件读出
readjson=json.load(coco)
print(readjson)