I am trying to take care of an error that cv2.imwrite keeps throwing, it keeps reaching the exact same image in a folder and then saying "-215:Assertion failed" at the cv2.imwrite line and I am not having much luck writing fail safes for that type of error, it is reading correctly so I have no idea why it wont write.
I have tried these two methods:
writeStatus = cv2.imwrite('output/'+ i, cropped)
if writeStatus is True:
print('Image Written')
else:
print('Error saving photo')
cv2.imwrite('rejected/'+ i, image)
if cv2.imwrite('output/'+ i, cropped) == True:
print('Image write succeeded')
else:
if cv2.imwrite('rejected/'+ i, image)== True:
print ('Cropped image could not be written, sent to rejects')
else:
print('writing error, script stopped')
break
I have no idea why it wont save the image, it seems to hate only this particular one so far, even if the image is alone in a folder it wont write it, I honesty dont care as long as I can output images like that to the reject folder instead of it killing the whole script.
EDIT I tried using
writeStatus = cv2.imwrite('output/'+ i, cropped)
if writeStatus is True:
print('Image Written')
else:
print('Error saving photo')
continue
and the error still stopped the script
Suggestion#1
If we look at the statement:
writeStatus = cv2.imwrite('output/'+ i, cropped)
'output/' + i supposed to be image name and cropped should be an image.
From what I understand, you want to save ith value, but the correct way is:
from os.path import join
filename = join('output', str(i) + '.png') # you can use other extensions like .jpg
cv2.imwrite(filename, cropped)
But, this is true if cropped variable is an image.
Suggestion #2
If a single image is causing a problem and you don't care, you could use try-except block and continue keyword
try:
writeStatus = cv2.imwrite(...)
.
.
except:
continue
Related
When I load a set of image files into a list and try to display one, it always renders as a gray box.The images are not gray boxes. The size of the image window displayed by openCV varies with the size of the actual image on file.
import cv2
import glob
import random
def loadImages(path):
imdir = path
ext = ['png', 'jpg', 'gif'] # Add image formats here
files = []
[files.extend(glob.glob(imdir + '*.' + e)) for e in ext]
#print("files", files)
images = [cv2.imread(file) for file in files]
return images
images = loadImages("classPhotos/")
print(str(len(images)), "images loaded")
#print(images)
cv2.imshow("image", random.choice(images))
tmp = input()
Add this 2 lines after cv2.imshow("image", random.choice(images)) to make it work properly.
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow shows the image instantly and then doesn't show it.
cv2.waitKey waits for a specific time/ keeps showing the image.
putting 0 as an argument makes it wait infinitely unless a key is pressed.
cv2.destroyAllWindows() helps close the window otherwise it gets stuck.
I'm currently facing an issue.
(started trying out python 3 hours ago)
So I tried making this discord bot where if a user sends an image, the bot would save it. My issue was the bot wasn't saving it in a certain folder (idk how also haha) so what I tried was I would copy the said image where it would create a new folder and that new folder is where the copied image would be placed. The original copies of the image would then be deleted, thus only leaving the image files in the folder.
My issue here now is that it's not consistent. It works on the first image input but it won't work if it would be attempted on the second time.
I would like to find a simpler way on being able to save an image file where it would then be directed to a folder rather than being saved in the same place as the python file.
#client.command()
async def save(ctx):
try:
url = ctx.message.attachments[0].url
except IndexError:
print("Error : No attachments")
await ctx.send("No attachments detected")
else:
imageName = str(uuid.uuid4()) + '.jpg'
r = requests.get(url, stream=True)
with open(imageName,'wb',) as out_file:
print('Saving image: ' + imageName)
shutil.copyfileobj(r.raw, out_file,)
images = [f for f in os.listdir() if '.jpg' in f.lower()]
os.mkdir('Images')
for image in images:
new_path = 'Images/' + image
shutil.move(image, new_path)```
You just need to change with open(imageName, 'wb') as out_file:
As it is it will save the image in the folder where the script is running, if you want to save them in the Images folder you just have to change that to with open("Images/" + imageName, 'wb') as out_file: or any other folder.
I think you're not giving a specific path, you can give a specific path using os.join(os.getcwd(),Images)
#client.command()
async def save(ctx):
try:
url = ctx.message.attachments[0].url
except IndexError:
print("Error : No attachments")
await ctx.send("No attachments detected")
else:
imageName = str(uuid.uuid4()) + '.jpg'
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(specific_path, 'wb') as f:
f.write(r.content)
I've been trying to figure out a way to get a user to choose an image from their computer that can be essentially uploaded into the program.
The code I have is:
elif cmd == 4: #image classification section
try:
image_list = []
for filename in glob.glob('Project/marvel/valid.jpg'): # assuming gif
im = Image.open(filename)
image_list.append(im)
except:
print("I'm sorry I can't guess who this person is")
But this doesn't do anything really so I think I've misunderstood what it does. Any advice/code/explanation will be appreciated.
I have a set of images that I am trying to process manually, so I wrote a simple plug-in to try and help make it a little less painful. The images are numbered sequentially. So when I finish working on one image I can hit a key combo and it saves the file with the correct name and opens the next one in the list. This all works fine.
The issue I have with the plug-in is that for newly opened images the undo-redo history does not work. I am not sure if I am not loading it in correctly, or if there is something that I have to set for the undo history to be enabled. When the new image is loaded the undo history is completely blank, and when I make changes to the image nothing new is added to it as I work on the file. This makes it difficult to do anything as a mistake means starting over. I am using the latest gimp version 2.8.18.
I am a complete newb at writing gimp plug-ins and built this from web examples, so any help to figure out why this is happening would greatly appreciated. Here is the code I wrote for the plug-in:
#!/usr/bin/python
from gimpfu import *
import os.path
def get_next_filename(filepath):
#Now figure out the next image to load
old_file = filepath.replace("\\", "/")
file_info = old_file.split('/')
#print file_info
name = file_info[len(file_info) - 1].replace(".JPG", "").replace("P", "")
print name
next_num = int(name) + 1
new_name = "P" + str(next_num) + ".JPG"
print new_name
file_info[len(file_info) - 1] = new_name
s = "/"
new_path = s.join(file_info)
print new_path
return new_path
def plugin_main(timg, tdrawable):
print "orig filename: ", timg.filename
new_filename = timg.filename.replace(".JPG", "_colored.JPG")
print "new filename: ", new_filename
layer = pdb.gimp_image_merge_visible_layers(timg, CLIP_TO_IMAGE)
if not os.path.isfile(new_filename):
pdb.gimp_file_save(timg, layer, new_filename, '?')
else:
pdb.gimp_message ("Failed to save segmented image. File " + new_filename + " already exists.")
print "Closing image"
#pdb.gimp_display_delete(gimp._id2display(0))
#Try to load one of the next 5 consecutive image numbers.
#If none found then quit plugin, else load it.
new_path = timg.filename
for i in range(0,5):
new_path = get_next_filename(new_path)
if os.path.isfile(new_path):
print new_path + " found. Loading it."
img = pdb.file_jpeg_load(new_path, new_path)
pdb.gimp_display_new(img)
return
pdb.gimp_message ("No more consecutive images were found in the folder.")
register(
"segmented_saver",
"Saves a segmented image with the correct name and opens next image.",
"Saves a segmented image with the correct name and opens next image.",
"DC",
"DC",
"2016",
"<Image>/Image/Save Segmented...",
"RGB*, GRAY*",
[],
[],
plugin_main)
main()
Just call image.enable_undo(). For example:
img = pdb.gimp_file_load('R:/1.jpg','1.jpg')
gimp.Display(img)
img.enable_undo()
I have a stored picture on my computer. I open it using the Python Image module. Then I crop this image into several pieces using this module. To conclude, I would like to upload the image via a POST request on a website.
Because that small images are PIL object, I converted each of them into StringIO to be able to send the form without having to save them on my PC.
Unfortunately, I encounter an error, whereas if the images are physically stored on my PC, there is no problem. I do not understand why.
You can visit the website here: http://www.noelshack.com/api.php
This is a very basic API that returns the link to the uploaded picture.
In my case, the problem is that returns nothing, at the end of the second image (no problem for the first).
Here is the programming code to crop the image into 100 pieces.
import requests
import Image
import StringIO
import os
image = Image.open("test.jpg")
width, height = image.size
images = []
for i in range(10):
for j in range(10):
crop = image.crop((i * 10, j * 10, (i + 1) * 10, (j + 1) * 10))
images.append(crop)
The function to upload an image:
def upload(my_file):
api_url = 'http://www.noelshack.com/api.php'
r = requests.post(api_url, files={'fichier': my_file})
if not 'www.noelshack.com' in r.text:
raise Exception(r.text)
return r.text
Now we have two possibilities. The first is to save each of the 100 images on disk and upload them.
if not os.path.exists("directory"):
os.makedirs("directory")
i = 0
for img in images:
img.save("directory/" + str(i) + ".jpg")
i += 1
for file in os.listdir("directory"):
with open("directory/" + file, "rb") as f:
print upload(f)
It works like a charm, but it is not very convenient. So, I thought to use StringIO.
for img in images:
my_file = StringIO.StringIO()
img.save(my_file, "JPEG")
print upload(my_file.getvalue())
# my_file.close() -> Does not change anything
The first link is printed, but the function raise the exception then.
I think the problem lies in the img.save(), because the same kind of for loop was not working to save to disk and then upload. In addition, if you add a time.sleep(1) between the uploads, it seems to work.
Any help would be welcome please, because I'm really stuck.
my_file.getvalue() returns a string. What you need is a file-like object, which my_file already is. And file like objects have a cursor, so to speak, which says where to read from or write to. So, if you do my_file.seek(0) before the upload, it should get fixed.
modify the code to:
for img in images:
my_file = StringIO.StringIO()
img.save(my_file, "JPEG")
my_file.seek(0)
print upload(my_file)