python - 打开 CV 断言失败,但文件名没有错误
问题描述
好的,所以我一直在做这个项目,我们从人行道上获取交通视频,检测汽车并读取他们的车牌。检测部分效果很好,我得到了满意的结果。现在我正在尝试提取汽车的边界框,并将它们保存为 jpg,并且我也只想要框架中某个区域的边界框。所以我写了这段代码,但每次在第 50 帧左右我都会收到一个断言错误。我认为视频没有任何问题,因为检测部分运行良好。我在第 54 行收到错误,
cv2.imwrite("frames\\"+str(number)+'.jpg', frametosave)
我都尝试了frames\\
,frames/
但两个路径名都有错误。在我被解雇之前请帮帮我。
import cv2
import numpy as np
video = cv2.VideoCapture("Resources/highway.mp4")
wh = 320
classpathname = 'Resources/coco.names'
classNames = []
videoWidth,videoHeight = int(video.get(3)), int(video.get(4))
size = (videoWidth, videoHeight)
result = cv2.VideoWriter('result.mp4', cv2.VideoWriter_fourcc(*'MJPG'),10, size)
with open(classpathname,'rt') as f:
classNames = f.read().rstrip('\n').split('\n')
configFile = "Resources/yolov3.cfg"
weights = "Resources/yolov3.weights"
net = cv2.dnn.readNetFromDarknet(configFile, weights)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
def findObjects(output, img):
h, w, c = img.shape
boundingbox = []
classIDs = []
confidences = []
for out in output:
for det in out:
scores = det[5:]
classID = np.argmax(scores)
confidence = scores[classID]
if confidence> 0.6:
width,height= int(det[2]*w), int(det[3]*h)
x,y = int((det[0]*w )-width/2), int((det[1]*h) -height/2)
boundingbox.append([x,y, width, height])
classIDs.append(classID)
confidences.append(confidence)
indices = cv2.dnn.NMSBoxes(boundingbox, confidences, 0.6, 0.3)
number = 1
for i in indices:
box = boundingbox[i]
x,y,w,h = box[0],box[1],box[2],box[3]
if(y+h>1000 and x+(w/2) <1000 ):
frametosave = img[y:y+h, x:x+w]
cv2.imwrite("frames/"+str(number)+'.jpg', frametosave)
number+=1
cv2.rectangle(img,(x,y), (x+w, y+h), (255,0,255),2)
cv2.putText(img, f'{classNames[classIDs[i]].upper()} {int(confidences[i]*100)}%', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,0,255), 2)
framenumber = 1
while True:
success, img = video.read()
if success:
blob = cv2.dnn.blobFromImage(img, 1 / 255, (wh, wh), [0, 0, 0], 1, crop=False)
net.setInput(blob)
print(framenumber)
framenumber +=1
layerNames = net.getLayerNames()
outputLayerNames = [layerNames[i - 1] for i in net.getUnconnectedOutLayers()]
outputs = net.forward(outputLayerNames)
findObjects(outputs, img)
if success:
result.write(img)
cv2.imshow("img", img)
if cv2.waitKey(1) & 0xFF == ord('s'):
break
video.release()
result.release()
这是我得到的错误
Traceback (most recent call last):
File "C:\Users\chhet\PycharmProjects\opencv\objectDetection.py", line 72, in <module>
findObjects(outputs, img)
File "C:\Users\chhet\PycharmProjects\opencv\objectDetection.py", line 54, in findObjects
cv2.imwrite("frames\\"+str(number)+'.jpg', frametosave)
cv2.error: OpenCV(4.5.4-dev) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:799: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'
OpenCV: FFMPEG: tag 0x47504a4d/'MJPG' is not supported with codec id 7 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'
Process finished with exit code 1
解决方案
So what I did was add a few conditions to check if the frame was valid and it worked. these are the conditions i checked:
if(x<0):
x=0
if(y<0):
y=0
frametosave = img[y:y+h, x:x+w]
if (x + w > videoWidth):
if (y + h > videoHeight):
frametosave = img[y:videoHeight, x:videoWidth]
frametosave = img[y:y + h, x:videoWidth]
if(y+h> videoHeight):
frametosave = img[y:videoHeight, x:x+w]
if frametosave.data:
print(frametosave.data)
cv2.imwrite("frames/" + str(number) + '.jpg', frametosave)
推荐阅读
- php - 在 laravel 5.8 中更新图像时文件输入表单的默认值
- apache - SVN 无法打开密码文件
- python - 如何在openpyxl中将列宽设置为bestFit
- javascript - 如何在每个完整的三个单词后插入换行符?
- tensorflow - 从 TFRecord 解析字段名称和类型
- java - 获取任意数量元素的所有组合
- r - 如何避免错误:$ 运算符对于使用 R 中的 precintcon 包的原子向量无效?
- rust - 如何从 Pin 中获取 Pin<&mut T>
>> - react-native - 检查 BottomNavigation - React Native 的渲染方法
- python - Pandas 中的 SQL 查询连接