I am trying to remove those raster files (in tif format) with all no value data(all the value in the file is -3.4028235e+38).
However, I found the os. remove() could not work, there is no file being deleted. The print statement also didn't work.
Could somebody tell me what the problem is with the code?
Cheers
from PIL import Image
import os
import numpy
directory = 'E:/data/'
for image in os.listdir(directory):
indiv = Image.open(directory + image)
elevMax = numpy.amax(indiv)
print(directory + image)
print(str(elevMax))
if elevMax == -3.4028235e+38:
print("it had the value")
os.remove(os.path.join(directory, image))
Here are some outputs for the code:
E:/data/filteredN01E116.tif
1907.05
E:/data/filteredN01E117.tif
-3.4028235e+38
E:/data/filteredN01E118.tif
-3.4028235e+38
E:/data/filteredN01E119.tif
-3.4028235e+38
E:/data/filteredN01E120.tif
1693.56
Problem solved.
It is just the problem of the type.
if elevMax == numpy.float32(-3.4028235e+38):
print("it had the value")
os.remove(os.path.join(directory, image))
That works! Thanks for all of your comments.
Related
This is my attempt:
import os
from PIL import Image
directory = r'../Icons/ico'
for filename in os.listdir(directory):
if filename.endswith(".ico"):
print(os.path.join(directory, filename))
img = Image.open(os.path.join(directory,filename))
sizes = img.info['sizes']
for i in sizes:
img.size = i
print(img.size)
size_in_string = str(img.size)
img.save('png/' + filename.strip('.ico') + size_in_string + '.png')
else:
continue
I'm afraid that this code is not grabbing the separate ico files and instead, grabbing the largest ico file and resizing it. Can someone please help me?
According to your title.
Here is how to convert a ico to png through python.
from PIL import Image
filename = 'image.ico'
img = Image.open(filename)
img.save('image.png')
#Optinally to save with size
icon_sizes = [...]
img.save('image.png', sizes=icon_sizes)
I am pretty sure you can adapt it in your code.
you can give a try to :
https://www.convertapi.com/ico-to-png
Code snippet is using ConvertAPI Python Client
convertapi.api_secret = '<YOUR SECRET HERE>'
convertapi.convert('png', {
'File': '/path/to/my_file.ico'
}, from_format = 'ico').save_files('/path/to/dir')
In addition, we do have a question in stackoverflow.com:
How to convert an .ICO to .PNG with Python?
or you can just change the end of the .ico file to .png
I am using OpenCV to try and process an image for my python class.
to load the image we are asked to retrieve a fully qualified path from the user and then also check if the path is valid. If the path is invalid I need to print a warning message and then terminate the function using return None. If the path is valid I want to print a success message and then return the value of the variable that I read the image into.
here is the code I have so far:
import cv2
import os
img_path = input("Enter a fully qualified path for an image: ")
#define a function to load an image
def img_loader():
try:
img = cv2.imread(img_path)
#exists = os.path.isfile(img_path) #I used this in my if/else statement
print("Success! The image path exists")
return ReturnValue(img)
except Exception:
print("WARNING: The file path you entered was incorrect.")
return None
when I run this script it gets the user input and then returns nothing at all (even when I commented out the 'return None' command)
I know that the path I'm using is correct but I'm not sure if I'm using the cv2.imread command correctly.
I've tried using both if/else and try/except for checking the path but I got the same result with both
How can I get my script to read the image into a variable and then return its value to the screen. Note: my teacher said that the value returned should be some sort of list
Thanks for the help, I was finally able to get it to work with this code.
import numpy as np
import cv2
import os
image_path = input("Enter a fully qualified path for an image: ")
#define a function to load an image
def img_loader(img_path):
exists = os.path.isfile(img_path)
if exists:
img = cv2.imread(img_path)
print("Success! The image path exists")
return img
else:
print("WARNING: The file path you entered was incorrect.")
return None
load=img_loader(image_path)
print(load)
I named all of the files in my folder, yet when I run the code it simply returns nothing as the file's filename attribute
if __name__ == '__main__':
print("Your Program Here")
images = glob.glob("uncropped/*.jpg")
for image in images:
with open(image, 'rb') as file:
img = Image.open(file)
print(img.filename)
print("open")
input()
This code returns nothing as the file name. What should I do?
The problem is you're opening the image file yourself with the built-in open() and passing that to Image.open(). Frankly, I agree the documentation is a little ambiguous about this scenario — I suppose a real file is a "file-like object".
Regardless, if you let PIL open the file it works:
import glob
from PIL import Image
folder = "*.jpg"
if __name__ == '__main__':
print("Your Program Here")
images = glob.glob(folder)
for image in images:
img = Image.open(image)
print(img.filename)
print("open")
If you really need the attribute to be there for some reason, a workaround is to just add it yourself:
if __name__ == '__main__':
print("Your Program Here")
images = glob.glob(folder)
for image in images:
with open(image, 'rb') as file:
img = Image.open(image)
img.filename = image # Manually add attribute.
print(img.filename)
print("open")
I am trying to extract all formats of images from pdf. I did some googling and found this page on StackOverflow. I tried this code but I am getting this error:
I am using python 3.x and here is the code I am using. I tried to go through comments but couldn't figure out. Please help me resolve this.
Here is the sample PDF.
import PyPDF2
from PIL import Image
if __name__ == '__main__':
input1 = PyPDF2.PdfFileReader(open("Aadhaar1.pdf", "rb"))
page0 = input1.getPage(0)
xObject = page0['/Resources']['/XObject'].getObject()
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
mode = "RGB"
else:
mode = "P"
if xObject[obj]['/Filter'] == '/FlateDecode':
img = Image.frombytes(mode, size, data)
img.save(obj[1:] + ".png")
elif xObject[obj]['/Filter'] == '/DCTDecode':
img = open(obj[1:] + ".jpg", "wb")
img.write(data)
img.close()
elif xObject[obj]['/Filter'] == '/JPXDecode':
img = open(obj[1:] + ".jp2", "wb")
img.write(data)
img.close()
I was reading some comments and going through links and found this problem solved on this page. Can someone please help me implement it?
It is the PyPDF2 library error. Try uninstalling and installing the library with changes or you can see the changes in the GitHub and mark the changes.I hope that will work.
As of today, I'm still getting the error NotImplementedError: unsupported filter /DCTDecode
I've PyPDF2 v 1.26.0 installed, using Python3 3.7.5. My Python code is the same as above.
Is there a solution yet?
Same error for me with Python 3.9 and PyPDF2 1.26 at time of this writing.
data = xObject[obj].getData()
was the problem line. My PDF had JPG images, and that line was not working because of same NotImlemented exception.
Changing the line for the /DCTDecode part to;
data = xObject[obj]._data
kind of worked for me. This gives plain JPG stream in the pdf.
So ie separate data = ... lines for each if/filter section, though not tried the JP2 part.
Im trying to make a function which needs as input an image file in jpg format and outputs an array every time i call it. This is what i achieved so far:
import scipy.misc as sm
import numpy as np
from PIL import Image
def imagefunc(image):
try:
i = Image.open(image)
if i.format == 'jpg':
return i.format == 'jpg'
except OSError: # Checking for different possible errors in the input file
print ('This is not a jpg image! Input has to be a jpg image!')
return False
except FileNotFoundError: # Another check for error in the input file
print ('No image was found! Input file has to be in the same directory as this code is!')
return False
imgarray = np.array(sm.imread(image, True))
return imgarray
The problem is that when i call it, "imagefunc(kvinna)" to open a jpeg picture it outputs: NameError: name 'kvinna' is not defined. What am i missing here? Is the code wrong or is it file directory problem? Thanks
Reading and Writing Images
You are not opening the image correctly, hence the Name Error
i = Image.open(image) # image should be "image_name.ext"
here image should be "kvinna.jpeg" with the extension.
so the function call will be: imagefunc("kvinna.jpeg") further check or either jpeg or jpg in your function definition.
Image.open(image) returns an Image object, later check the extension for it.