深度學習paddle加載模型之后使用模型報錯
在使用paddle加載模型成功之后,只要運行到使用模型的語句就會報錯。最開始我一直以為是這個語句本身的問題或是模型的問題,
爆出問題是 無法讀取某些圖片 can not read the image file : D:\Walker\testv01\zhen\frame2.jpg
但是我在百度之后很多的答案並不是我想的問題,大部分都在說是加載圖片的問題,可能是雖然圖片的格式看着是jpg或是其他,但是只是將圖片的后綴修改jpg,沒有轉碼,我嘗試轉碼后並沒有用。后來我通過來百度飛槳的群里詢問,得到可能是路徑不是存在中文的原因,上面我給出路徑是已經修改成中文的,所以沒有問題。windows中路徑問題有很多,所以我們盡量進行英文命名,不用中文命名,有的 / 和 \並存在一個路徑上也可能會有問題,比如 D:\Walker\testv01\zhen/frame2.jpg,盡量保持統一。
可以讀取圖片之后我以為問題解決了,但是又出現了其他的問題,
運行到使用模型的語句就是報出如下錯誤:
Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized. OMP: Hi
這是在pycharm中運行的報出錯誤,如果使用jupyter notebook 甚至會直接運行到這句的時候,瞬間內核崩潰,但是這個問題簡單,只需要添加兩行代碼:
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
問題就解決了
所有的代碼:
import matplotlib import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import paddlex as pdx import cv2 from random import shuffle, seed base = 'D:\File\pascalvoc/VOCdevkit/VOC2012/' from paddlex.det import transforms train_transforms = transforms.Compose([ transforms.MixupImage(mixup_epoch=250), transforms.RandomDistort(), transforms.RandomExpand(), transforms.RandomCrop(), transforms.Resize(target_size=512, interp='RANDOM'), transforms.RandomHorizontalFlip(), transforms.Normalize(), ]) eval_transforms = transforms.Compose([ transforms.Resize(target_size=512, interp='CUBIC'), transforms.Normalize(), ]) #base = 'D:\軟件\谷歌瀏覽器下載/pascalvoc/VOCdevkit/VOC2012/' train_dataset = pdx.datasets.VOCDetection( data_dir=base, file_list=os.path.join(base, 'train_list.txt'), label_list='labels.txt', transforms=train_transforms, shuffle=True) eval_dataset = pdx.datasets.VOCDetection( data_dir=base, file_list=os.path.join(base, 'val_list.txt'), label_list='labels.txt', transforms=eval_transforms) print("開始加載模型") model = pdx.load_model('YOLOv3/best_model') model.evaluate(eval_dataset, batch_size=1, epoch_id=None, metric=None, return_details=False) import cv2 import time import numpy as np import matplotlib.pyplot as plt import paddlex as pdx import cv2 def video2frame(videos_path, frames_save_path, time_interval): ''' :param videos_path: 視頻的存放路徑 :param frames_save_path: 視頻切分成幀之后圖片的保存路徑 :param time_interval: 保存間隔 :return: ''' vidcap = cv2.VideoCapture(videos_path) success, image = vidcap.read() count = 0 a = 2 while success: success, image = vidcap.read() count += 1 if count % time_interval == 0: cv2.imencode('.jpg', image)[1].tofile(frames_save_path + "/frame%d.jpg" % count) image_name = 'D:/Walker/testv01/zhen/frame'+ str(a)+'.jpg' start = time.time() result = model.predict(image_name, eval_transforms) print('infer time:{:.6f}s'.format(time.time()-start)) print('detected num:', len(result)) im = cv2.imread(image_name) font = cv2.FONT_HERSHEY_SIMPLEX threshold = 0.01 for value in result: xmin, ymin, w, h = np.array(value['bbox']).astype(np.int) cls = value['category'] score = value['score'] if score < threshold: continue cv2.rectangle(im, (xmin, ymin), (xmin+w, ymin+h), (0, 255, 0), 4) cv2.putText(im, '{:s} {:.3f}'.format(cls, score), (xmin, ymin), font, 0.5, (255, 0, 0), thickness=2) cv2.imwrite(image_name, im) plt.figure(figsize=(15,12)) plt.imshow(im[:, :, [2,1,0]]) a = a + 2 # if count == 20: # break print(count) if __name__ == '__main__': videos_path = 'qq01.mp4' frames_save_path = 'D:/Walker/testv01/zhen/' time_interval = 2 # 隔一幀保存一次 video2frame(videos_path, frames_save_path, time_interval)
import cv2
import os
import numpy as np
from PIL import Image
def frame2video(im_dir, video_dir, fps):
im_list = os.listdir(im_dir)
im_list.sort(key=lambda x: int(x.replace("frame", "").split('.')[0])) # 最好再看看圖片順序對不
img = Image.open(os.path.join(im_dir, im_list[0]))
img_size = img.size # 獲得圖片分辨率,im_dir文件夾下的圖片分辨率需要一致
# fourcc = cv2.cv.CV_FOURCC('M','J','P','G') #opencv版本是2
fourcc = cv2.VideoWriter_fourcc(*'XVID') # opencv版本是3
videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)
# count = 1
for i in im_list:
im_name = os.path.join(im_dir + i)
frame = cv2.imdecode(np.fromfile(im_name, dtype=np.uint8), -1)
videoWriter.write(frame)
# count+=1
# if (count == 200):
# print(im_name)
# break
videoWriter.release()
print('finish')
if __name__ == '__main__':
im_dir = 'D:/Walker/testv01/zhen/' # 幀存放路徑
video_dir = 'D:/Walker/testv01/video/suc.avi' # 合成視頻存放的路徑
fps = 20 # 幀率,每秒鍾幀數越多,所顯示的動作就會越流暢
frame2video(im_dir, video_dir, fps)
這樣就能分割視頻成指定的幀,然后進行每個幀中的行人以及其他物品的識別了。
最后再將每一幀的圖片進行組合就成為視頻了。