如何在 Django 中使用 FileSystemStorage 上传由 OpenCV 修改的图像文件?
How to upload an Image File modified by OpenCV using FileSystemStorage in Django?
我正在从用户那里获取上传的图像,然后将其发送到 YOLO 模型,然后 returns 给我一张图像。
我想将返回的图像存储在我的本地目录中,然后将其显示在用户界面上。
这是 views.py
的代码,它接收图像并将其发送到 Yolo 模型,
def predictImage(request):
# print(request)
# print(request.POST.dict())
fileObj = request.FILES['filePath']
fs = FileSystemStorage()
filePathName = fs.save(fileObj.name, fileObj)
filePathName = fs.url(filePathName)
testimage = '.'+filePathName
# img = image.load_img(testimage, target_size=(img_height, img_width))
img = detect_image(testimage)
filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
filePathName = fs.url(filePathName)
这是 YOLO 模型的函数,它使用 OpenCV 读取图像(图像作为函数的参数发送)然后 returns 该图像,
import numpy as np
import cv2
def detect_image(img_path):
confidenceThreshold = 0.5
NMSThreshold = 0.3
modelConfiguration = 'cfg/yolov3.cfg'
modelWeights = 'yolov3.weights'
labelsPath = 'coco.names'
labels = open(labelsPath).read().strip().split('\n')
np.random.seed(10)
COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
image = cv2.imread(img_path)
(H, W) = image.shape[:2]
#Determine output layer names
layerName = net.getLayerNames()
layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
net.setInput(blob)
layersOutputs = net.forward(layerName)
boxes = []
confidences = []
classIDs = []
for output in layersOutputs:
for detection in output:
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
if confidence > confidenceThreshold:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype('int')
x = int(centerX - (width/2))
y = int(centerY - (height/2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
#Apply Non Maxima Suppression
detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
if(len(detectionNMS) > 0):
for i in detectionNMS.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
color = [int(c) for c in COLORS[classIDs[i]]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
return image
#cv2.imshow('Image', image)
#cv2.waitKey(0)
这一行,
filePathName = fs.save(fileObj.name + "_result", img)
我收到以下错误,
'numpy.ndarray' object has no attribute 'read'
我不确定如何解决这个问题。我尝试搜索如何使用 FileSystemStorage 存储 OpenCV 修改后的文件,但没有找到任何帮助。有人可以帮我解决这个问题吗?
您可以使用cv2
库的imwrite
功能将您的文件存储在本地目录中,即
对于你的情况,只需这样做,
img = detect_image(testimage)
cv2.imwrite(fileObj.name+"_result.jpg", img=img)
我正在从用户那里获取上传的图像,然后将其发送到 YOLO 模型,然后 returns 给我一张图像。
我想将返回的图像存储在我的本地目录中,然后将其显示在用户界面上。
这是 views.py
的代码,它接收图像并将其发送到 Yolo 模型,
def predictImage(request):
# print(request)
# print(request.POST.dict())
fileObj = request.FILES['filePath']
fs = FileSystemStorage()
filePathName = fs.save(fileObj.name, fileObj)
filePathName = fs.url(filePathName)
testimage = '.'+filePathName
# img = image.load_img(testimage, target_size=(img_height, img_width))
img = detect_image(testimage)
filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
filePathName = fs.url(filePathName)
这是 YOLO 模型的函数,它使用 OpenCV 读取图像(图像作为函数的参数发送)然后 returns 该图像,
import numpy as np
import cv2
def detect_image(img_path):
confidenceThreshold = 0.5
NMSThreshold = 0.3
modelConfiguration = 'cfg/yolov3.cfg'
modelWeights = 'yolov3.weights'
labelsPath = 'coco.names'
labels = open(labelsPath).read().strip().split('\n')
np.random.seed(10)
COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
image = cv2.imread(img_path)
(H, W) = image.shape[:2]
#Determine output layer names
layerName = net.getLayerNames()
layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
net.setInput(blob)
layersOutputs = net.forward(layerName)
boxes = []
confidences = []
classIDs = []
for output in layersOutputs:
for detection in output:
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
if confidence > confidenceThreshold:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype('int')
x = int(centerX - (width/2))
y = int(centerY - (height/2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
#Apply Non Maxima Suppression
detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
if(len(detectionNMS) > 0):
for i in detectionNMS.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
color = [int(c) for c in COLORS[classIDs[i]]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
return image
#cv2.imshow('Image', image)
#cv2.waitKey(0)
这一行,
filePathName = fs.save(fileObj.name + "_result", img)
我收到以下错误,
'numpy.ndarray' object has no attribute 'read'
我不确定如何解决这个问题。我尝试搜索如何使用 FileSystemStorage 存储 OpenCV 修改后的文件,但没有找到任何帮助。有人可以帮我解决这个问题吗?
您可以使用cv2
库的imwrite
功能将您的文件存储在本地目录中,即
对于你的情况,只需这样做,
img = detect_image(testimage)
cv2.imwrite(fileObj.name+"_result.jpg", img=img)