Strange Pillow exception while saving cropped image - python

We have the following code:
img = Image.open(FileSystemStorage().path(relpath))
coords = [
cd['crop_start_x'],
cd['crop_start_y'],
cd['crop_end_x'],
cd['crop_end_y']
]
cropped_img = img.crop(coords)
cropped_path = "%s-cropped%s" % os.path.splitext(relpath)
tasks.delete_temporary_file.delay(fss.path(relpath))
cropped_img.save(fss.path(cropped_path))
When trying to save the cropped image, we get a strange "Not a valid number of quantization tables. Should be between 1 and 4." exception, just in one of our environments.
The strangest part is that the code might work sometimes even though the crop or the image doesn't change
Has anyone a lead on this?
We are using Pillow 2.8.1, python 2.7.6 and Ubuntu server 12.04

Basically, the problem originated on a conflicting PIL installation in one of the app servers. It was hard to find since they were hiding behind a load balancer, so the error would pop out sometimes
When we issued pip freeze on the console, we found out that in one of the servers we had both PIL and Pillow installed.
Upon removing both of them and reinstalling Pillow, we solved the issue.
Just to make it clear:
pip uninstall PIL
pip uninstall Pillow
pip install Pillow
And then, just restart the web server.
As others have stated, another possible cause is the use of:
import Image
That statement works only for PIL and should be avoided.
We should always use:
from PIL import Image

Related

How do I get Pillow ImageOps.contain to work when inside VS Code?

I have VS Code on a Mac.
Pillow is installed and version verified as 8.3.2 via Pip list in the terminal window of VS Code. I have confirmed via the pillow docs that the ImageOps.contain() is part of 8.3.
My problem is that when I use the terminal, type python and run the following, it works perfectly:
from PIL import Image, ImageOps
im = Image.open("images/Barcelona.jpg")
print(im.format, im.size, im.mode)
im = ImageOps.contain(im, (800, 800), method=3)
im.show()
Preview pops right up and shows me the picture.
When I put the exact code into VS Code or build a .py file with Nano, I get an error message which is shown in this image:
I've verified the right version of Python, Pillow, and such. Any help or pointers would be greatly appreciated.
This turns out to be a problem with what I can only call nested environments and/or a conflict between Anaconda and Workspaces. I'm not really sure but when I used the _version import to figure out a) what VS Code thought and then b) figured out the environment Pip was reporting on, I deactivated up one level, upgraded the (base) to the 8.3 version and all ran fine. The knowledge on importing the version variable to see precisely what the code is importing came from the question asked below and was invaluable.

Problem displaying image opencv+python using imshow + waitKey

I have recently upgraded my python/opencv for a project to python 3.7 + opencv 4.3.0 and now I have an issue with opencvs imshow. I am running Ubuntu 18.04 and am using conda venvs.
I tried to rerun this piece of code multiple times and half the time it correctly displays the white image, and half the time it displays the image below (1). The printed output (2) is always the same. I tried changing it from waitKey(0) to waitKey(1000) but that doesn't make a difference. Still about half the time a tiny black image is all I see.
Does anybody know how to debug this? I tried looking at Pycharms log files but they dont have any more details. I also tried running it straight from the command line but that gives the same issue. Also tried to remove the environment and created a fresh one, reinstalled opencv and got the same issues. When I create a 3.6 environment I don't have the issue, but that's no longer an option. I need python3.7 for some other packages that don't support certain features in 3.6.
I received a warning that libcanberra gtk was missing, and found that in another post that it could cause issues. So I installed it using sudo apt install libcanberra-gtk-module libcanberra-gtk3-module and the warning went away. Sadly the issue did not...
import numpy as np
import cv2
if __name__ == '__main__':
img = np.ones((255, 255, 3), dtype=np.uint8)*255
print(img.shape)
print(img.dtype)
print(img.min())
print(img.max())
cv2.imshow("i", img)
cv2.waitKey(0)
screenshot of the code + result
console output
I think there is no problem. The left-upper part of the image is white as it is supposed to be. The rest is undefined. I recommend equating green and blue channels to zero and leaving only red channel as 255 in order to make sure that is the case.
I solved it in this way:
if cv2.waitKey(0):
pass

OpenCV 4.0.0 SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set

Hello I am trying to create a facial recognition program but I have a peculiar error:
here is my code:
import cv2 as cv
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_cascade = cv.CascadeClassifier("lbpcascade_frontalface.xml")
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
and this error is the output
SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set
I have "lbpcascade_frontalface.xml" in the working directory so that shouldn't be an issue
if it helps when I enter
cv.__version__
I get
'4.0.0'
New Answer
OpenCV seems to now have a directory dedicated to cascades, they are placed in data and I am seeing something like this floating around in tutorials now
haar_cascade_face = cv.CascadeClassifier('data/haarcascade/haarcascade_frontalface_default.xml')
You may have to find where data is on your machine or the above my work. I have not touched this project since I finished it in early 2019.
Bear in mind this only works for frontal face, if you want to use Haar's Cascade for eyes that is a separate file.
old answer
Turns out I didn't need to download another file and use it because opencv comes with it this little bit of code worked
cv.CascadeClassifier(cv.data.haarcascades + "haarcascade_frontalface_default.xml")
Well I was in this same problem, as #TylerStrouth mentioned this code snippet doesn't work :
cv.CascadeClassifier(cv.data.haarcascades + "haarcascade_frontalface_default.xml")
because there are no haarcascades files in data directory if you have just installed opencv in a standard format of pip install opencv-python or sudo apt-get install python3-opencv
You will get an error something similar to this stackoverflow question, therein is the mentioned solution that worked for me, that is if you're using python3 then you need also to install opencv-contrib-python before running the above code snippet.
pip install opencv-contrib-python
which has full package (contains both main modules and contrib/extra modules)
As explained by #TylerStrouth above opencv has a directory of cascades in which the cascade files are available, I also faced the same problem while running the code for face detection on Ubuntu 16.04 and solved it as follows
Get the location of opencv using
whereis opencv
Mine was in /usr/share/opencv
Check whether the cascades are present in that location and copy paste the location in cv2.CascadeClassifier along with the required haarcascade
I have encountered same issue in little different way.
I was using Jupiter notebook to execute code here
I copied XML file from here and created a XML file in current Jupiter directory, when loading this files using below:
classifier = CascadeClassifier('haarcascade_frontalface_default.xml')
Its returned me error :
SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set
So, I tried other way, removed this file, and downloaded actual file as XML format in current directory, which resolved my issue.
I was having the same error when i was using hogcascade_pedestrians.xml to detect pedestrians from a local video and i was reading the hogcascade_pedestrians.xml as follows:
pedestrainsClassifier = cv2.CascadeClassifier("hogcascade_pedestrians.xml")
Of which you should read it as follows:
pedestrainsClassifier = cv2.CascadeClassifier(f"{cv2.data.haarcascades}hogcascade_pedestrians.xml")
Alternatively you can do it as follows:
pedestrainsClassifier = cv2.CascadeClassifier(cv2.data.haarcascades +"hogcascade_pedestrians.xml")
Good luck
Change your code as follows, this worked for me
har_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'har.xml')
On version 3.4.9.33 of opencv-python (pip show opencv-python, Windows) the below line works fine: trained_face_data = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

PIL decoder JPEG not available Raspberry

i'm trying to utilize PIL to open a jpeg image and assign it to a Tkinter's label.
However whenever i try to open the image i get the same problem as this guy
I tried all the suggestions he got and also the ones i found here but it doesn't seem to fix, by installing PIL or Pillow(i tried that too) during the setup i get :
*** TKINTER support not available
*** JPEG support not available
And whenever i run my code i get an IOError: decoder jpeg not available
I'm using python 2.7.
Can someone provide a good method to make PIL or Pillow work with jpeg support? I've been googling extensively for two days, but all the possible fixes that i found don't seem to work for me
Installing libjpeg-dev should do the trick, as proposed by the link you provided. But if it doesn't help (I ran into that as well) you can consider upgrading to Pillow 3, it looks like you are running Pillow 2. This also helped me getting rid of the errors, don't know why exactly..

X11 Tkinter + PIL + py2app = IOError cannot identify image file

I have a problem with a python program (python 2.7.3, X11 Tkinter, py2app 0.6.4, MacOS X 10.7.4) that I'm trying to export to py2app. The problem only started occurring in the standalone py2app-ified app version of the program. When I run the python source file from which the app was created, the problem does not exist, so I feel it must have something to do with the py2app export.
The problem: When I start the GUI, the first time I try to load a valid image file, the image fails to load, and I get the following error from the PIL Image module:
File "Image.pyc", line 1980, in open
IOError: cannot identify image file
When I then (without closing the GUI or anything) try to open the exact same file, it loads perfectly, no errors or problems. This happens every time, with any image file I try - the first attempt to load fails, subsequent attempts succeed. I should add that after that first error, no image files ever fail to load - even if they are different from the first one.
A few notes:
- The image file is a sequence, and is very large (around 300 MB), so to speed up the loading process, I use a mmap. I have tried removing the mmap step, and handing a regular file object directly to ImagePIL.open it directly, and the problem is unaffected.
- I also tried seeking to the beginning of the file before giving it to ImagePIL.open, but that had no effect.
- The py2app setup file is pretty vanilla - it just includes a few config files and an icon.
Here is the relevant part of the offending image load function:
import Image as ImagePIL
import mmap as m
...
...
def loadImage(self):
errorLog.debug("Attempting to open image \""+self.filenameVar.get()+"\"")
try:
if self.fileMap is not None:
self.fileMap.close()
imageFile = open(self.filenameVar.get(), 'r')
self.fileMap = m.mmap(imageFile.fileno(), 0, prot=m.PROT_READ)
# self.fileMap.seek(0)
self.imageSeries = ImagePIL.open(self.fileMap)
imageFile.close()
except(IOError):
errorLog.exception("Failed to open image \""+self.filenameVar.get()+"\"")
return
I'm pretty stumped - any ideas? Thanks in advance!
Edit: I should add that Tkinter, PIL, and py2app were installed using MacPorts 2.1.2, in the off chance that helps.
It seems that py2app does not include PIL's image plugins into the application bundle even though one of the py2app recipes tries to ensure that they are included.
One thing you could try is to build with "python setup.py py2app --packages=PIL" and then use "import PIL.Image as ImagePIL" to use it.
I don't understand yet why the PIL recipe doesn't work, it might be something in the way MacPorts builds python packages (I don't use MacPorts myself).
The problem is the result of inconsistency between Pillow version 3.0.0 and py2app.
I suggest two solution to avoid PIL (Pillow)
Use opencv instead of PIL.
uninstall the current version of Pillow and install a previous one like 1.7.8

Categories