ShanghaiTech数据集是适用于密集人群计数领域的经典公开数据集,其分为A\B两部分,原始数据集的图像尺寸各不相同,且标注文件和图像尺寸相对应,在使用过程中,可能需要对于图像的尺寸进行调整,同时也需要修改标注文件;
文件结构:
文件夹:afterProcess(带标注示意图),ground_truch(原始数据集mat文件),img(原始数据集图像文件),new_ground_truth(新生成的mat文件),new_image(新生成的图像文件),均在同一个文件夹下;
为了方便,.py文件也在此目录下;
其中主要涉及.mat文件的读写与cv2修改图像尺寸;(仅供学习参考以及个人回忆)
代码如下:将图像都统一为 384*512大小
import os
import sys
from scipy.io import loadmat
import cv2
import numpy as np
import scipy.io
imagePath=".img/"
groundPath=".ground_truth/"
savePath=".afterProcess/"
newGroundPath = ".new_ground_truth/"
# 针对shanghaitech A B 数据集
def createMat():
"""
根据原来的mat文件生成新的修改过图像尺寸的mat文件
"""
files = os.listdir(imagePath) # 读取文件夹下的图片
for file in files:
image = cv2.imread(imagePath+file)
height = image.shape[0]
width = image.shape[1]
x_xi = round(384/height, 2)
y_xi = round(512/width, 2)
fileName = file.replace('IMG_','')
fileName = fileName.replace('.jpg','')
print(fileName)
m=loadmat(groundPath+"GT_IMG_"+fileName+".mat")
coordinates=m["image_info"][0][0][0][0][0]
for i in range(0, len(coordinates)):
m["image_info"][0][0][0][0][0][i][0] = round(coordinates[i][0]*y_xi, 2)
m["image_info"][0][0][0][0][0][i][1] = round(coordinates[i][1]*x_xi, 2)
scipy.io.savemat(newGroundPath+"GT_IMG_"+fileName+".mat", m)
def showLablledImage():
"""
调整图像的尺寸,并且根据修改后的mat文件在调整过尺寸的图像上将标注显示出来
"""
files = os.listdir(imagePath) # 读取文件夹下的图片
for file in files:
image = cv2.imread(imagePath+file)
image = cv2.resize(image,(512,384),interpolation=cv2.INTER_CUBIC)
fileName = file.replace('IMG_','')
fileName = fileName.replace('.jpg','')
print(fileName)
cv2.imwrite("./justPoint/new_image/"+file, image, [int(cv2.IMWRITE_JPEG_QUALITY),95])
m=loadmat(newGroundPath+"GT_IMG_"+fileName+".mat")
point_size = 1
point_color = (0, 0, 255) # BGR
thickness = 4 # 0 、4、8
coordinates=m["image_info"][0][0][0][0][0]
for coor in coordinates:
cv2.circle(image, (int(coor[0]),int(coor[1])), point_size, point_color, thickness)
cv2.imwrite(savePath+file, image, [int(cv2.IMWRITE_JPEG_QUALITY),95])
# 使用顺序:1)先用createMat生成mat文件;2)用showLablledImage
#showLablledImage()
createMat()