gpt4 book ai didi

python - 在 GCE 上部署后的 Django FileNotFound 错误

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:34 24 4
gpt4 key购买 nike

我正在开发一个 Django 2 项目,其中我的根目录中有一个 img 文件夹,我将一些图像保存到该文件夹​​中,然后从该文件夹创建一个 zip 存档并发送到浏览器。它在我的本地系统上运行良好,但当我使用 Gunicorn 将它部署在 Google Compute Engine 上的 Liux 实例上时,它会返回此存储库的错误。

这是我的 views.py

class PerformImgSegmentation(generics.ListAPIView):
def get(self, request, *args, **kwargs):
img_url = self.kwargs.get('encoded_url')
print(img_url)
print('get request')

def create_pascal_label_colormap():
colormap = np.zeros((256, 3), dtype=int)
ind = np.arange(256, dtype=int)

for shift in reversed(range(8)):
for channel in range(3):
colormap[:, channel] |= ((ind >> channel) & 1) << shift
ind >>= 3

return colormap

def label_to_color_image(label):
if label.ndim != 2:
raise ValueError('Expect 2-D input label')

colormap = create_pascal_label_colormap()

if np.max(label) >= len(colormap):
raise ValueError('label value too large.')

return colormap[label]

def vis_segmentation(image, seg_map):
seg_image = label_to_color_image(seg_map).astype(np.uint8)

# BasicSource Modification in the original Image for segmentation
imgOrigin = cv2.imread('originImage.png')
seg_image_gray = cv2.cvtColor(seg_image, cv2.COLOR_BGR2GRAY)
(thresh, im_bw) = cv2.threshold(seg_image_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# Creating the Mask of the Image via Segmentation Map
cv2.imwrite('MaskedImage.png', seg_image)
maskedImage = cv2.bitwise_and(imgOrigin, imgOrigin, mask=im_bw)
# Generating the transparent image on the base of Masked Image.
outputImgAlpha = cv2.cvtColor(maskedImage, cv2.COLOR_BGR2RGBA)
bg_color = outputImgAlpha[0][0]
maskNew = np.all(outputImgAlpha == bg_color, axis=2)
outputImgAlpha[maskNew] = [0, 0, 0, 0]
image_bgr_transparent = cv2.cvtColor(outputImgAlpha, cv2.COLOR_RGB2BGRA)
cv2.imwrite('ExtractedImage.png', image_bgr_transparent)

# #################### END of PROCESSING MODIFICATION ##########################
unique_labels = np.unique(seg_map)

LABEL_NAMES = np.asarray([
'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',
'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike',
'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tv'
])

# @title Select and download models {display-mode: "form"}

MODEL_NAME = 'mobilenetv2_coco_voctrainaug' # @param ['mobilenetv2_coco_voctrainaug', 'mobilenetv2_coco_voctrainval', 'xception_coco_voctrainaug', 'xception_coco_voctrainval']

_DOWNLOAD_URL_PREFIX = 'http://download.tensorflow.org/models/'
_MODEL_URLS = {
'mobilenetv2_coco_voctrainaug':
'deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz',
'mobilenetv2_coco_voctrainval':
'deeplabv3_mnv2_pascal_trainval_2018_01_29.tar.gz',
'xception_coco_voctrainaug':
'deeplabv3_pascal_train_aug_2018_01_04.tar.gz',
'xception_coco_voctrainval':
'deeplabv3_pascal_trainval_2018_01_04.tar.gz',
}
_TARBALL_NAME = 'deeplab_model.tar.gz'

model_dir = tempfile.mkdtemp()
tf.gfile.MakeDirs(model_dir)

download_path = os.path.join(model_dir, _TARBALL_NAME)
print('downloading model, this might take a while...')
urllib.request.urlretrieve(_DOWNLOAD_URL_PREFIX + _MODEL_URLS[MODEL_NAME],
download_path)
print('download completed! loading DeepLab model...')

MODEL = DeepLabModel(download_path)
print('model loaded successfully!')

# @title Run on sample images {display-mode: "form"}

SAMPLE_IMAGE = '' # @param ['image1', 'image2', 'image3']

# ENTER YOUR IMAGE URL
IMAGE_URL = img_url # @param {type:"string"}

_SAMPLE_URL = ('https://github.com/tensorflow/models/blob/master/research/'
'deeplab/g3doc/img/%s.jpg?raw=true')

def run_visualization(url):
"""Inferences DeepLab model and visualizes result."""
try:
f = urllib.request.urlopen(url)
jpeg_str = f.read()
original_im = Image.open(BytesIO(jpeg_str))
except IOError:
print('Cannot retrieve image. Please check url: ' + url)
return

print('running deeplab on image %s...' % url)
resized_im, seg_map = MODEL.run(original_im)
originImgArray = np.array(resized_im)
originalBGRImage = cv2.cvtColor(originImgArray, cv2.COLOR_RGB2BGR)
cv2.imwrite('originImage.png', originalBGRImage)

vis_segmentation(resized_im, seg_map)
print('Foreground Extraction is Done... check ExtractedImage.png file')

image_url = IMAGE_URL or _SAMPLE_URL % SAMPLE_IMAGE
run_visualization(image_url)
# Genearte a Zip archive which Includes all images

filelist = ["img/ExtractedImage.png", "img/MaskedImage.png"]

byte_data = BytesIO()
zip_file = zipfile.ZipFile(byte_data, "w")

for file in filelist:
filename = os.path.basename(os.path.normpath(file))
zip_file.write(file, filename)
zip_file.close()

response = HttpResponse(byte_data.getvalue(), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=files.zip'

# Print list files in zip_file
zip_file.printdir()

return response

这是它返回的错误:

Internal Server Error: /api/http://i.imgur.com/tSYZBuU.jpg/
Traceback (most recent call last):
File "/root/ImgSegEnv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/root/ImgSegEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/root/ImgSegEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/root/ImgSegEnv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/root/ImgSegEnv/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/root/ImgSegEnv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/root/ImgSegEnv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/root/ImgSegEnv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/root/ImgSeg/Imgseg/views.py", line 189, in get
zip_file.write(file, filename)
File "/usr/local/lib/python3.6/zipfile.py", line 1581, in write
zinfo = ZipInfo.from_file(filename, arcname)
File "/usr/local/lib/python3.6/zipfile.py", line 482, in from_file
st = os.stat(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'img/ExtractedImage.png'

甚至我已经通过运行此命令为 img 文件夹设置了权限:

sudo chmod -R g+w img

最佳答案

您试图打开当前工作目录中的文件,因为您没有指定路径。您需要改用绝对路径:

import os
from PROJECT import settings

filelist = [os.path.join(settings.BASE_DIR, 'img/ExtractedImage.png'),
os.path.join(settings.BASE_DIR, 'img/MaskedImage.png')]

这将获取img目录的绝对路径。

关于python - 在 GCE 上部署后的 Django FileNotFound 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52208582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com