How to use temporary file from form upload - Python Django - python

I have a form where users can upload up to 1,000 images at a time. I have changed my FILE_UPLOAD_MAX_MEMORY_SIZE in Django settings to 0 so all files uploaded via a form are written to a temp directory in my root folder.
I am then trying to process the images with OpenCV.
original_img = cv2.imread(temp_image.temporary_file_path())
gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY)
temp_image.temporary_file_path()
This returns the absolute file path of the temp image in a string format
So I put that in the cv2.imread, however, it creates a NoneType instead of a numpy array like it should and then my program cannot run when it reaches
gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY)
How do I read the temporary file into OpenCV?
Any help is much appreciated.

in your case save that file to another path in your system first
import os
os.rename(temp_image.temporary_file_path(), another_file_path_in_your_system)
original_img = cv2.imread(another_file_path_in_your_system)
gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY)

Related

Cannot save multiple files with PIL save method

I have modified a vk4 converter to allow for the conversion of several .vk4 files into .jpg image files. When ran, IDLE does not give me an error, but it only manages to convert one file before ending the process. I believe the issue is that image.save() only seems to affect a single file and I have been unsuccessful in looping that command to extend to all other files in the directory.
Code:
import numpy as np
from PIL import Image
import vk4extract
import os
os.chdir(r'path\to\directory')
root = ('.\\')
vkimages = os.listdir(root)
for img in vkimages:
if (img.endswith('.vk4')):
with open(img, 'rb') as in_file:
offsets = vk4extract.extract_offsets(in_file)
rgb_dict = vk4extract.extract_color_data(offsets, 'peak', in_file)
rgb_data = rgb_dict['data']
height = rgb_dict['height']
width = rgb_dict['width']
rgb_matrix = np.reshape(rgb_data, (height, width, 3))
image = Image.fromarray(rgb_matrix, 'RGB')
image.save('sample.jpeg', 'JPEG')
How do I prevent the converted files from being overwritten while using the PIL module?
Thank you.
It is saving every file, but since you are always providing the same name to each file (image.save('sample.jpeg', 'JPEG')), only the last one will be saved and all the other ones will be overwritten. You need to specify different names to every file. There are several ways of doing it. One is adding the index when looping using enumerate():
for i, img in enumerate(vkimages):
and then using the i on the name of the file when saving:
image.save(f'sample_{i}.jpeg', 'JPEG')
Another way is to use the original filename and replace the extension. From your code, it looks like the files are .vk4 files. So another possibility is to save with the same name but replacing .vk4 to .jpeg:
image.save(img.replace('.vk4', '.jpeg'), 'JPEG')

Trying to pull a random ".tif" image from folder and print image

I have created a definition that loads every image from a called folder. I am now trying to create a code that will either 1) load a specific image when indexed, and/or 2) load an image at random. I have attached two screenshots of my code and the error I am receiving.
https://i.stack.imgur.com/nQKrV.png
https://i.stack.imgur.com/toXkI.png
It looks like you need to concatenate the directory path with the file name:
with open(os.path.join(rat110_GF_path, random_filename)) as file
lines = file.readlines()

Save images using Pillow without overwriting already saved images

I want to save around 12000 images generated from a particular code. I will be able to save these images only using my Project VPN which keeps disconnecting some times and then the entire process of saving takes place by overwriting already saved images and taking again a lot of time.
How do I avoid this?
from PIL import Image
dirc = os.path.join(r"C:\\", "DATASET", "Images", f"{measurename}")
if not os.path.exists(dirc):
os.makedirs(dirc)
gray_image_cropped.save(os.path.join(dirc, f"{id}_seg{obj}.tif"))
Check whether the file exists:
from PIL import Image
dirc = os.path.join(r"C:\\", "DATASET", "Images", f"{measurename}")
if not os.path.exists(dirc):
os.makedirs(dirc)
outfile = os.path.join(dirc, f"{id}_seg{obj}.tif"
if not os.path.exists(outfile):
gray_image_cropped.save(outfile))

Saving an Image file using binary Files - pyspark

How can I save Image file(JPG format) into my local system. I used BinaryFiles to load the pictures into spark, converted them into Array and processed them. Below is the code
from PIL import Image
import numpy as np
import math
images = sc.binaryFiles("path/car*")
imagerdd = images.map(lambda (x,y): (x,(np.asarray(Image.open(StringIO(y)))))
did some image processing and now key has path and value has Array for Image
imageOutuint = imagelapRDD.map(lambda (x,y): (x,(y.astype(np.uint8))))
imageOutIMG = imageOutuint.map(lambda (x,y): (x,(Image.fromarray(y))))
How can I save the Image to local/HDFS system, I see there is no option pertaining to it.
If you want to save data to local file system just collect as local iterator and use standard tools to save files records by records:
for x, img in imagerdd.toLocalIterator():
path = ... # Some path .jpg (based on x?)
img.save(path)
Just be sure to cache imagerdd to avoid recomputation.

python PIL acces multiple images from a single image file

I have written a python script to Delta compress an image. The image file format is .tif which contains 8 images. When I use the normal code ...
org_Image = Image.open(image)
org_Data = org_Image.load()
... I can only access the first image. How do I go about accessing the other ones?
You use org_Image.seek(org_Image.tell() + 1) to get the next one.
In PIL seek moves you to a given frame, (with an IO_Error if it doesn't exist), and tell reports the current frame number.

Categories

Resources