Я работаю над проектом Django 2, в котором у меня есть папка img
внутри моего корневого каталога, и я сохраняю некоторые изображения в эту папку, затем создаю zip-архив из этой папки и отправляю в браузер. Он работал нормально в моей локальной системе, но когда я развернул его на экземпляре Liux в Google Compute Engine с помощью Gunicorn, он возвращает ошибку для этого репозитория.
Вот мои 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