I am learning image processing with scipy. I experience some diffuculties with rather basic opeartions as saving an image. Here is my code:
import scipy
from scipy import misc
img=misc.imread("C:\\..\\name.jpg")
misc.imsave("image.jpg",img)
I obtain error message:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
misc.imsave("image.jpg",img)
File "C:\Python27\lib\site-packages\scipy\misc\pilutil.py", line 158, in imsave
im.save(name)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1461, in save
fp = builtins.open(fp, "wb")
IOError: [Errno 13] Permission denied: 'image.jpg'
Try to use the full path when saving:
misc.imsave(r'C:\path\image.jpg', img)
your error is a permission error, so probably you do not have access to write in the current directory. You can also change the current directory using os.chdir( newpath ).
The code above creates a file in a given directory but it is empty (0 bytes) and produces error in the IDLE:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
misc.imsave(r"D:\Darek\back3.jpg", img)
File "C:\Python27\lib\site-packages\scipy\misc\pilutil.py", line 158, in imsave
im.save(name)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1467, in save
save_handler(self, fp, filename)
File "C:\Python27\lib\site-packages\PIL\JpegImagePlugin.py", line 557, in _save
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 466, in _save
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 395, in _getencoder
return encoder(mode, *args + extra)
TypeError: function takes at most 11 arguments (13 given)
Hmm, your code works fine for me in the dreampie shell
import scipy
from scipy import misc
img = misc.imread("C:/folder/name.jpg")
misc.imsave("C:/folder2/image.jpg",img)
I don't know PIL well enough, but there seems to be an encoder issue involved. Have you tried your code with different image files?
Related
Python 3.9, Pycharm
Am trying to run this code to use the live webcam to take a screenshot, than process that screenshot and identify any text in the screenshot
Code I have put in:
import cv2
from PilLite import Image
import pytesseract
camera=cv2.VideoCapture(0)
def NIC_tesseract():
path_to_tesseract=r"Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract"
pytesseract.pytesseract.tesseract_cmd=path_to_tesseract
#Imagepath='test1.jpg'
pytesseract.tesseract_cmd=path_to_tesseract
text=print(pytesseract.image_to_string(Image.open('test1.jpg'),lang="eng"))
print(text[:-1])
while True:
_,PicturePhoto=camera.read()
cv2.imshow('Text Detection',PicturePhoto)
if cv2.waitKey(30)& 0xFF==ord('s'):
cv2.imwrite('test1.jpg',PicturePhoto)
break
camera.release()
cv2.destroyAllWindows()
NIC_tesseract()
Error Coming Up:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 254, in run_tesseract
proc = subprocess.Popen(cmd_args, **subprocess_args())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 947, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1819, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/NicAveray/PycharmProjects/FacialRecognition/Trial 2.py", line 25, in
NIC_tesseract()
File "/Users/NicAveray/PycharmProjects/FacialRecognition/Trial 2.py", line 13, in NIC_tesseract
text = pytesseract.image_to_string(PicturePhoto, lang="eng")
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 416, in image_to_string
return {
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 419, in
Output.STRING: lambda: run_and_get_output(*args),
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 286, in run_and_get_output
run_tesseract(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 258, in run_tesseract
raise TesseractNotFoundError()
pytesseract.pytesseract.TesseractNotFoundError: Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract is not installed or it's not in your PATH. See README file for more information.
You assign 'Image' the return from camera.read() while at the same time it is a function imported from PilLite. I think the return from camera.read() is actually a numpy array, which explains the error message. Change the variable name of the return I would suggest.
I'm not sure why you added a print in the line of the OCR. However, please try passing the full path directly.
text = pytesseract.image_to_string(r"D:/.../test1.jpg", lang="eng")
I'm just worried that the time taken to write the image and reading it is too much, so you should read the frames directly by passing your variable "PicturePhoto" to tesseract like this:
text = pytesseract.image_to_string(PicturePhoto, lang="eng")
I am trying to serialize/deserialize spaCy documents (setup is Windows 7, Anaconda) and am getting errors. I haven't been able to find any explanations. Here is a snippet of code and the error it generates:
import spacy
nlp = spacy.load('en')
text = 'This is a test.'
doc = nlp(text)
fout = 'test.spacy' # <-- according to the API for Doc.to_disk(), this needs to be a directory (but for me, spaCy writes a file)
doc.to_disk(fout)
doc.from_disk(fout)
Traceback (most recent call last):
File "<ipython-input-7-aa22bf1b9689>", line 1, in <module>
doc.from_disk(fout)
File "doc.pyx", line 763, in spacy.tokens.doc.Doc.from_disk
File "doc.pyx", line 806, in spacy.tokens.doc.Doc.from_bytes
ValueError: [E033] Cannot load into non-empty Doc of length 5.
I have also tried creating a new Doc object and loading from that, as shown in the example ("Example: Saving and loading a document") in the spaCy docs, which results in a different error:
from spacy.tokens import Doc
from spacy.vocab import Vocab
new_doc = Doc(Vocab()).from_disk(fout)
Traceback (most recent call last):
File "<ipython-input-16-4d99a1199f43>", line 1, in <module>
Doc(Vocab()).from_disk(fout)
File "doc.pyx", line 763, in spacy.tokens.doc.Doc.from_disk
File "doc.pyx", line 838, in spacy.tokens.doc.Doc.from_bytes
File "stringsource", line 646, in View.MemoryView.memoryview_cwrapper
File "stringsource", line 347, in View.MemoryView.memoryview.__cinit__
ValueError: buffer source array is read-only
EDIT:
As pointed out in the replies, the path provided should be a directory. However, the first code snippet creates a file. Changing this to a non-existing directory path doesn't help as spaCy still creates a file. Attempting to write to an existing directory causes an error too:
fout = 'data'
doc.to_disk(fout) Traceback (most recent call last):
File "<ipython-input-8-6c30638f4750>", line 1, in <module>
doc.to_disk(fout)
File "doc.pyx", line 749, in spacy.tokens.doc.Doc.to_disk
File "C:\Users\Username\AppData\Local\Continuum\anaconda3\lib\pathlib.py", line 1161, in open
opener=self._opener)
File "C:\Users\Username\AppData\Local\Continuum\anaconda3\lib\pathlib.py", line 1015, in _opener
return self._accessor.open(self, flags, mode)
File "C:\Users\Username\AppData\Local\Continuum\anaconda3\lib\pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
PermissionError: [Errno 13] Permission denied: 'data'
Python has no problem writing at this location via standard file operations (open/read/write).
Trying with a Path object yields the same results:
from pathlib import Path
import os
fout = Path(os.path.join(os.getcwd(), 'data'))
doc.to_disk(fout)
Traceback (most recent call last):
File "<ipython-input-17-6c30638f4750>", line 1, in <module>
doc.to_disk(fout)
File "doc.pyx", line 749, in spacy.tokens.doc.Doc.to_disk
File "C:\Users\Username\AppData\Local\Continuum\anaconda3\lib\pathlib.py", line 1161, in open
opener=self._opener)
File "C:\Users\Username\AppData\Local\Continuum\anaconda3\lib\pathlib.py", line 1015, in _opener
return self._accessor.open(self, flags, mode)
File "C:\Users\Username\AppData\Local\Continuum\anaconda3\lib\pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Username\\workspace\\data'
Any ideas why this might be happening?
doc.to_disk(fout)
must be
a path to a directory, which will be created if it doesn't exist.
Paths may be either strings or Path-like objects.
as the documentation for spaCy states in https://spacy.io/api/doc
Try changing fout to a directory, it might do the trick.
EDIT:
Examples from the spacy documentation:
for doc.to_disk:
doc.to_disk('/path/to/doc')
and for doc.from_disk:
from spacy.tokens import Doc
from spacy.vocab import Vocab
doc = Doc(Vocab()).from_disk('/path/to/doc')
When trying to follow the example posted here. The code segment is the same as given in the example
import matplotlib.image as mpimg
filename = "/home/MarshOrchid.jpg"
image = mpimg.imread(filename)
# Print out its shape
print(image.shape)
Running the code gives the following error message. What could be the underlying cause?
Traceback (most recent call last):
File "test2.py", line 5, in <module>
image = mpimg.imread(filename)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux- x86_64.egg/matplotlib/image.py", line 1304, in imread
im = pilread(fname)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1283, in pilread
return pil_to_array(image)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1400, in pil_to_array
x = toarray(im)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1383, in toarray
x_str = im.tobytes('raw', im.mode)
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/Image.py", line 678, in tobytes
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/ImageFile.py", line 235, in load
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/ImageFile.py", line 59, in raise_ioerror
OSError: broken data stream when reading image file
When trying to do the following in the PIL python library:
Image.open('Apple.gif').save('Apple.pgm')
the code fails with:
Traceback (most recent call last):
File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_comm.py", line 765, in doIt
result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec)
File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_vars.py", line 376, in evaluateExpression
result = eval(compiled, updated_globals, frame.f_locals)
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1439, in save
save_handler(self, fp, filename)
File "/usr/lib/python2.7/dist-packages/PIL/PpmImagePlugin.py", line 114, in _save
raise IOError, "cannot write mode %s as PPM" % im.mode
IOError: cannot write mode P as PPM
The code works fine with conversion to BMP, but JPG also fails.
Strange thing is, a different file(JPG to PGM), works ok.
Other format conversion. That is:
Image.open('Apple.gif').save('Apple.bmp')
works.
Any idea why?
You need to convert the image to RGB mode to make this work.
im = Image.open('Apple.gif')
im = im.convert('RGB')
im.save('Apple.pgm')
I have a problem in python. I'm using scipy, where i use scipy.io to load a .mat file. The .mat file was created using MATLAB.
listOfFiles = os.listdir(loadpathTrain)
for f in listOfFiles:
fullPath = loadpathTrain + '/' + f
mat_contents = sio.loadmat(fullPath)
print fullPath
Here's the error:
Traceback (most recent call last):
File "tryRankNet.py", line 1112, in <module>
demo()
File "tryRankNet.py", line 645, in demo
mat_contents = sio.loadmat(fullPath)
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/mio.py", line 111, in loadmat
matfile_dict = MR.get_variables()
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/miobase.py", line 356, in get_variables
getter = self.matrix_getter_factory()
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/mio5.py", line 602, in matrix_getter_factory
return self._array_reader.matrix_getter_factory()
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/mio5.py", line 274, in matrix_getter_factory
tag = self.read_dtype(self.dtypes['tag_full'])
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/miobase.py", line 171, in read_dtype
order='F')
TypeError: buffer is too small for requested array
The whole thing is in a loop, and I checked the size of the file where it gives the error by loading it interactively in IDLE.
The size is (9,521), which is not at all huge. I tried to find if I'm supposed to clear the buffer after each iteration of the loop, but I could not find anything.
Any help would be appreciated.
Thanks.