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.
Related
so i made a small script that converts a youtube vidoe to an audio then downloads it but i have a small problem..
i want to loop my code and it wont break untill i close it . i want it to ask me again to enter new link
from pafy import new
link = input("Enter the video link: ")
video = new(link)
best = video.getbestaudio()
filename = best.download(filepath="C:\\Users\\Admin\\Desktop\\MP3 Downloader\\Downloads")
im a beginner to python and any feedback will help me :)
You can use while loop as below to keep it continue
import time
while True:
link = input("Enter the video link: ")
video = new(link)
best = video.getbestaudio()
filename = best.download(filepath="C:\\Users\\Admin\\Desktop\\MP3 Downloader\\Downloads")
time.sleep(5)
Maybe you should add a loop if you want it to loop ;). For instance :
from pafy import new
from time import sleep
while 1 :
link = input("Enter the video link: ")
video = new(link)
best = video.getbestaudio()
filename = best.download(filepath="C:\\Users\\Admin\\Desktop\\MP3 Downloader\\Downloads")
sleep(1)
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
Hopefully this is a quick one for someone. its been annoying me for a while now.
I can create the directory and save the images to the directory where the script is ran, but i cannot figure how to save the images to its specific folder created for that specific advert.
Would someone be able to shed some light on this please?
gundir = soup.find("title").text #keep - folder creation for each advert using title
gun_folders = os.makedirs(gundir)
for img in imgs:
clean = re.compile('src=".*?"')
strings = clean.findall(str(img))
for string in strings:
imgUrl = string.split('"')[1]
filename = imgUrl.split('/')[-1]
resp = requests.get(imgUrl, stream=True)
local_file = open(filename, 'wb')
resp.raw.decode_content = True
shutil.copyfileobj(resp.raw, local_file)
del resp
I understand the above code does what its supposed to do, but its not enough for what i wish it to do.
Could someone point me in the direction on how to achieve what i'm after?
Thanks!
String concatenation
local_file = open('{}/{}'.format(gun_folders ,filename), 'wb')
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)