I have a program which has a loop in it.
In this loop I load images from a file.
But there are some not usable images, that I don`t want to sort by hand.
I have this code:
img = Image.open("downloads/parrot/" + pictures[i])
img = img.resize((150,150))
img.save("Validation/parrot/" + "picture" + str(i) + ".png")
i = i + 1
I tried to use the try except method, but it always stopped the program.
Is there any way to use an if loop, like "if imageisuseful() = false:"?
Or do you may have any other Ideas?
Thank you for your help.
If you don't want your try / except to stop your code, you can pass :
try:
img = Image.open("downloads/parrot/" + pictures[i])
img = img.resize((150,150))
img.save("Validation/parrot/" + "picture" + str(i) + ".png")
i = i + 1
except:
pass # pictures[i] raised an exception here
Depending on where the error is happening (either at the open or the resize) you might need to move things around:
img = Image.open("downloads/parrot/" + pictures[i])
try:
img = img.resize((150,150))
img.save("Validation/parrot/" + "picture" + str(i) + ".png")
i = i + 1
except:
print("FILE {} DOESN'T WORK".format(pictures[i]))
Related
I'm writing a code to convert GeoTiff files to png.
Pillow didn't work for me. Hence I am using gdal. Am I missing something in the code?
The code is as below:
from osgeo import gdal
import os
options_list = ['-ot Byte','-of PNG']
options_string = " ".join(options_list)
in_tif = r"E:\some\path\tif_folder"
out_png = r"E:\some\other\path\png_folder"
list_tif = os.listdir(in_tif)
for x in list_tif:
in_tif = in_tif + "\\" + x
out_png = out_png + "\\" + x
gdal.Translate(out_png,in_tif,options=options_string)
It actually gave me a file with .tif extension which I previously failed to notice. Thus, I used replace function to change tif to png. There was also very basic flaw in the for loop because of which the file was kept getting added.
new code which works:
from osgeo import gdal
import os
options_list = ['-ot Byte','-of PNG']
options_string = " ".join(options_list)
in_tif = r"E:\some\path\tif_folder"
out_png = r"E:\some\other\path\png_folder"
list_tif = os.listdir(in_tif)
for x in list_tif:
indi_tif = in_tif+"\\" + x
print(in_tif)
indi_png = out_png + "\\" + x
try:
gdal.Translate(indi_png.replace(".tif",".png"),indi_tif,options=options_string)
except:
print("Failed files,",indi_tif)
I am sending an extracted list with xpath but it doesn't work with xpath
it works like this URL1
url = ['http://images/productos/on-line/items/large/nb/de/nbdell1tc73.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_1.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_2.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_3.jpg'
]
it does not work URL2
url = sel.xpath('//section[#class="product-images js-product-images-container"]//img/#src')
result url.path
'url': ['http://images/productos/on-line/items/large/nb/de/nbdell1tc73.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_1.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_2.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_3.jpg'],
this code recepte the url
i = 0
for url22 in url:
try:
imagen_content = requests.get(url22).content
image_file = io.BytesIO(imagen_content)
imagen = Image.open(image_file).convert('RGB')
path = './imagenes/' + '_' + str(i) + '.jpg'
with open(path, 'wb')as f:
imagen.save(f, "JPEG", quality=85)
except Exception as ex:
print(ex)
print("ERROR")
i += 1
With the first url it works, with the second one it doesn't.
How do I make it work with url2?
it turned out, I need to put url.get () url22.get()
i = 0
for url22 in url:
try:
imagen_content = requests.get(url22.get()).content
image_file = io.BytesIO(imagen_content)
imagen = Image.open(image_file).convert('RGB')
path = './imagenes/' + '_' + str(i) + '.jpg'
with open(path, 'wb')as f:
imagen.save(f, "JPEG", quality=85)
except Exception as ex:
print(ex)
print("ERROR")
i += 1
I wrote the code and now I have problem that the code finde only the first value (for example only img, we have img2 too, but it went to another picture) and copy only one, but we have 2 possibilities.
for i in df_list:
img = (filepath + i + ".jpg")
img2 = (filepath + i + "-1" + ".jpg")
img3 = (filepath + i + "-2" ".jpg")
img4 = (filepath + i + "-3" + ".jpg")
img5 = (filepath + i + "-4" + ".jpg")
img6 = (filepath + i + " -5" + ".jpg")
try:
shutil.copy(img, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img6, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img2, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img3, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img4, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img5, newpath, follow_symlinks=True)
except:
with open("C:/Users/"+user+"/Desktop/J/"+datum+"/"+"Napake.txt", "a") as text_file:
print("Slika za ident {} ne obstaja.\n".format(i), file=text_file)
I neeed help, thank you for answers.
Rather than copying the try,except you can loop over the filenumbers and try copy each file. and print an error if there is an exception.
save_path = "C:/Users/" + user + "/Desktop/J/" + datum + "/" + "Napake.txt"
for folder in df_list:
for index in range(6):
if index == 0:
img = filepath + folder + ".jpg"
else:
img = f"{filepath}{folder}-{index}.jpg"
try:
shutil.copy(img6, newpath, follow_symlinks=True)
with open(save_path, "a") as text_file:
text_file.write(f"Slika za ident {folder}-{i} ne obstaja.\n")
except Exception as e:
print('could not copy file')
print(e)
I would also recommend having a look at this answer to see how to copy all files in a directory.
I have some code that I wrote that downloads images from a website. The way that it currently works it needs to guess what the file extension will be for the url it will be downloading from. The block of code that does that looks like this:
for imageLink in imageLinks:
try:
urllib.request.urlretrieve(imageLink + ".png", str(threadName) + "/" + str(count) + ".png")
except:
try:
urllib.request.urlretrieve(imageLink + ".jpg",str(threadName) + "/" + str(count) + ".png")
except:
try:
urllib.request.urlretrieve(imageLink + ".gif",str(threadName) + "/" + str(count) + ".gif")
except:
urllib.request.urlretrieve(imageLink + ".webm",str(threadName) + "/" + str(count) + ".webm")
As it stands the code is relying on a fail in order to try something else.
I wanted to know if their is a way to have this functionality but to basically just look better. These methods will give identical errors if they fail so I want to just go through them sequentially until one works
for ext in ('.png', '.jpg', '.gif', '.webm'):
try:
urllib.request.urlretrieve(imageLink + ext, str(threadName) + "/" + str(count) + ext)
break
except:
pass
You can use a try/except block inside a function and return None if the control goes to the except statement. You can optimize the for loop according to your own needs. One example is here:
def get_url(link1, link2):
try:
requestData = urllib.request.urlretrieve(link1, link2)
except:
return None
return requestData
for imageLink in imageLinks:
data = urllib.request.urlretrieve(imageLink + ".png", str(threadName) + "/" + str(count) + ".png")
if data == None:
data = urllib.request.urlretrieve(imageLink + ".jpg",str(threadName) + "/" + str(count) + ".png")
if data == None:
data = urllib.request.urlretrieve(imageLink + ".gif",str(threadName) + "/" + str(count) + ".gif")
if data == None:
urllib.request.urlretrieve(imageLink + ".webm",str(threadName) + "/" + str(count) + ".webm")
Please can someone help me?
I have been trying to write in an html file that I create myself, a bunch of jpg files just to display them, but I can't seem to do anything, and there have been so many errors till I got even anywhere...
Can anyone please help, I have no experience in html from python.
Here's the code:
def download_images(img_urls, dest_dir):
#html_file = open("index.html", 'rb')
html_file = open("index.html", 'w')
print("Retrieving...")
html_file.write("""<verbatim>""")
html_file.write("""<html>""")
html_file.write("""<body>""")
for url,i in zip(img_urls,range(len(img_urls))):
image_opened = urllib.request.urlopen(url)
urllib.request.urlretrieve(url, "img" + str(i) + ".jpg")
img_tag = r'"""<img"""' + str(i) + r' src="/edu/python/exercises/img' + str(i) + r'"""">"""'.format(urllib.request.urlretrieve(url, "img" + str(i) + ".jpg"))
html_file = open("index.html", 'w')
html_file.write(urllib.request.urlretrieve(url, "img" + str(i) + ".jpg"))
#print('<img' + str(i) + ' src="/edu/python/exercises/img"' + str(i) + '>')
html_file.write(r""""</body>""""")
html_file.write("""</html>""")
html_file.close()
I will go through what you have so far and comment on it.
The first few bits look okay until
image_opened = urllib.request.urlopen(url)
This line opens a stream to the requested url, you don't do anything with this and you don't need it as you download the image using:
urllib.request.urlretrieve(url, "img" + str(i) + ".jpg")
You then create the html img line, which you have overcomplicated a bit. You are trying to produce a line that reads something like this:
<img src='img1.jpg' />
What you seem to be doing in:
img_tag = r'"""<img"""' + str(i) + r' src="/edu/python/exercises/img' + str(i) + r'"""">"""'.format(urllib.request.urlretrieve(url, "img" + str(i) + ".jpg"))
Is starting to create the right string but then you attempt to download the jpg again. You just need to do create the string as follows:
img_tag = "<img src='src" + str(i) + ".jpg' />"
You then open the html output file again using:
html_file = open("index.html", 'w')
You don't need to do this as you still have the file open from when you opened it at the beginning of the method.
You then attempt to write the html string to the file doing;
html_file.write(urllib.request.urlretrieve(url, "img" + str(i) + ".jpg"))
This is instead trying to download the jpg again and output the result into the html file. Instead you want to write the img_tag by:
html_file.write(img_tag)
You write the end of the file okay and close it.
html_file.write(r""""</body>""""")
html_file.write("""</html>""")
html_file.close()
Once you fix this you should have a function that looks like:
import urllib.request
def download_images(img_urls, dest_dir):
#html_file = open("index.html", 'rb')
html_file = open("index.html", 'w')
print("Retrieving...")
html_file.write("<html>")
html_file.write("<body>")
for url,i in zip(img_urls,range(len(img_urls))):
urllib.request.urlretrieve(url, "img" + str(i) + ".jpg") # Downloads image
img_tag = "<img src='img" + str(i) + ".jpg' />"
html_file.write(img_tag)
html_file.write("</body>")
html_file.write("</html>")
html_file.close()
That you can call with something like:
download_images(["a.jpg","b.jpg"],"")