I am trying to convert a PDF to JPG, main goal is to have a thumbnail so that the user can preview the PDF within the application.
Apparently ImageMagick is a good way to do this, yet so far I failed to get it to convert the file.
import subprocess
params = ['convert', '-density 300 -resize 220x205', 'dummy.pdf', 'thumb.jpg']
subprocess.check_call(params)
So this is what I am getting instead of having the file converted:
Unzulässiger Parameter - 300
Traceback (most recent call last):
File "pdf_preview_test.py", line 4, in
subprocess.check_call(params)
File "C:\Users\EliasMessner\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 347, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['convert', '-density 300 -resize 220x205', 'dummy.pdf', 'thumb.jpg']' returned non-zero exit status 4.
I couldn't find any info about the problem. It looks like the "300" parameter is illegal but IMHO it is used correctly.. Help would be much appreciated. Thanks.
As you are on Windows the code could be trying the built in Windows convert program. You do not say what version on Imagemagick you are using; V7 uses magick as opposed to convert which can prevent this problem.
If you allowed Imagemagick to add convert to the environmental path on install it would probably not be a problem - it never has for me on multiple installs.
You could try changing convert to the full path to convert surrounding the path in " ". You can rename the convert program e.g. myconvert and use that in the program rather than convert.
I would try a Imagemagick command out in the command line to prove it works as well first.
Related
(My operating system is macOS)
I am making a discord bot which allows a user to create graphics and display using an image through python's turtle module.
After creating the graphics I post-script the canvas to my desktop as an eps file with the user's username in the filename:
import turtle
...
Canvas = turtle.Screen()
Canvas.getcanvas().postscript(file=f"desktop/{context.author}'s_graphics.eps")
I attempted to output it as an eps file knowing that it wouldn't work but still worth a try:
import discord
...
await context.send(
embed=discord.Embed().set_image(url="attachment://graphics.png"),
file=discord.File(f"desktop/{context.author}'s_graphics.png","graphics.png")
)
But as expected it didn't work.
So I tried to directly convert it to a png file, if I were to do that by hand the file would become unreadable and if I convert it back to eps it would be readable again.
So then I used the PIL module to convert the eps file to png:
import turtle
from PIL import Image
...
Canvas = turtle.Screen()
Canvas.getcanvas().postscript(file=f"desktop/{context.author}'s_graphics.eps")
image=Image.open(f"desktop/{context.author}'s_graphics.eps") # Where macOS terminal error was raised
image.convert("RGBA") # Where Visual Studio Code error was raised
I had a few errors involving ghostscript being the root of the problem, I resolved them by installing ghostscript using homebrew because I didn't have it installed beforehand apparently.
But now I get two separate errors in two different command lines
If I were to run the script in the macOS terminal (and call the command in discord) I would get this error: FileNotFoundError: [Errno 2] No such file or directory: "desktop/Bossman#4404's_graphics.eps" - fair enough I can just get the absolute path or something. <- This error was raised
However, if I run the script in the Visual Studio Code terminal I get this error:
subprocess.CalledProcessError: Command '['gs', '-q', '-g719x675', '-r72.000000x72.000000', '-dBATCH', '-dNOPAUSE', '-dSAFER', '-sDEVICE=ppmraw', '-sOutputFile=/var/folders/ms/wv_n3bzs7zvctx07pqqzv__m0000gp/T/tmpg65g140v', '-c', '53 -59 translate', '-f', "desktop/Bossman#4404's_graphics.eps", '-c', 'showpage']' returned non-zero exit status 2.
I think it involves ghostscript again based off of the gs being an element in the array in the exception.
I went over several stackoverflow posts on this similar exception but in all of those posts they were directly using the subprocess module where I am not so Im not sure what to do.
How do I fix this? Or simply just make an eps to png file conversion?
Any other help would also be appreciated. <3
Edit:
Just to clarify I am not using turtle mainloop() or update() since I'm already running a loop being client.run(TOKEN) and I can't run simultaneous loops to my knowledge. (The discord loop is to run async functions.)
(Even removing image.convert("RGBA") I still get the same error at image.save())
I've just noticed at the very top of the exception it says:
Usage: gs [OPTIONS] COMMAND [ARGS]...
Try 'gs --help' for help.
Error: no such option: -q
Then comes in the
Traceback (most recent call last):
Code Edit:
import turtle
from PIL import Image
from os import system, path
...
directory = f"Users/family/Desktop/{context.author}'s_graphics"
Canvas = turtle.Screen()
Canvas.getcanvas().postscript(file=directory+".eps")
image = Image.open(path.realpath(directory+".eps"))
image.convert("RGBA") # Where error is raised
image.save(directory+".png",lossless=True)
await context.send(
embed=embed("").set_image(url="attachment://graphics.png"),
file=discord.File(directory+".png","graphics.png")
)
system(f"rm {directory}.png")
I m trying to use image_to_osd function of tesseract but I got this error for python 3.6, but when I test the same script in an other environment with python 3.8 it works !!, is there any configuration for python 3.6 or anything to do ?
angle_rotated_image = re.search('(?<=Rotate: )\d+',pytesseract.image_to_osd(rotated)).group(0)
error:
angle_rotated_image = re.search('(?<=Rotate: )\d+',pytesseract.image_to_osd(rotated)).group(0)
File "C:\Users\username\AppData\Roaming\Python\Python36\site-packages\pytesseract\pytesseract.py", line 543, in image_to_osd
}[output_type]()
File "C:\Users\username\AppData\Roaming\Python\Python36\site-packages\pytesseract\pytesseract.py", line 542, in <lambda>
Output.STRING: lambda: run_and_get_output(*args),
File "C:\Users\username\AppData\Roaming\Python\Python36\site-packages\pytesseract\pytesseract.py", line 287, in run_and_get_output
run_tesseract(**kwargs)
File "C:\Users\username\AppData\Roaming\Python\Python36\site-packages\pytesseract\pytesseract.py", line 263, in run_tesseract
raise TesseractError(proc.returncode, get_errors(error_string))
pytesseract.pytesseract.TesseractError: (1, 'Tesseract Open Source OCR Engine v5.0.0.20190623 with Leptonica Warning: Invalid resolution 0 dpi. Using 70 instead. Estimating resolution as 163 Warning. Invalid resolution 0 dpi. Using 70 instead. Too few characters. Skipping this page Error during processing.')
I ran into a similar problem when trying to determine rotation of a given document and trying to use pytesseract's image_to_osd(). It was working fine for me on MacOS with tesseract 4.1.1, but it wouldn't work on Windows with tesseract 5.0.0-alpha. After reading through many threads on the topic related to the OP's error and trying various things like passing --dpi and -c min_chararacters_to_try= with no success, I finally tried using a different version of tesseract on Windows, which finally solved my problem.
Status of image_to_osd():
(PASS) OS MacOS; tesseract 4.1.1; pytesseract 0.3.0; Python 3.6.5
(PASS) OS Windows; tesseract 4.1.0; pytesseract 0.3.0; Python 3.6.5
(FAIL) OS Windows; tesseract 5.0.0; pytesseract 0.3.0; Python 3.6.5
I think pytesseract 0.3.7 will probably work too, but I didn't test it.
Note that you can still get OP's error with this, but from what I tested it's much more reasonable now, e.g., with blank pages.
I'm using Linux Mint 18.1 and Python 3.5.2.
I have a library that currently works using Python 2.7. I need to use the library for a Python 3 project. I'm updating it and have run into a unicode problem that I can't seem to fix.
First, a file is created via tar cvjf tarfile.tbz2 (on a Linux system) and is later opened in the Python library as open(tarfile).
If I run the code as is, using Python 3, I get the following error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 11: invalid start byte
My first attempt at a fix was to open it as open(tarfile, encoding='utf-8') as I was under the impression that tar would just use what the file system gave it. When I do this, I get the same error (the byte value changes).
If I try with another encoding, say latin-1, I get the following error:
TypeError: Unicode-objects must be encoded before hashing
Which leads me to believe that utf-8 is correct, but I might be misunderstanding.
Can anyone provide suggestions?
I was going down the wrong path thinking this was some strange encoding problem. When it was just a simple problem with that fact that open() defaults to read as text (r). In Python 2 it's a no-op.
The fix is to open(tarfile, 'rb').
The head fake with unicode...should have seen this one coming. :facepalm:
subprocess.call('/Users/siddarthkrishnan/Desktop/Lion.jpg', shell = True)
126 giving me this in python 3.5 return of 126.
Why is the file not opening? It is giving return error 126.
Based on the path you pasted I assume you are on Windows. subprocess.call tries to invoke your jpg file as an executable (like *.exe, *.bat etc.) and fails because it isn't an executable. This is not a bug, this is the correct behavior.
If you want to launch the Windows Photo Gallery (or whatever program is set for the *.jpg file extension in your file associations), you can use os.startfile like this:
import os
os.startfile('/Users/siddarthkrishnan/Desktop/Lion.jpg')
Note: this solution works only on Windows.
I'm pretty new to Qt, Python and their combinations. I'm currently writing a QGIS plugin in python (I used QtCreator 2.1 (Qt Designer 4.7) to generate a .ui-file and am now trying to use it for a Quantum GIS plugin that's written in Python 2.5 (and running in the Quantum GIS Python 2.5 console)).
I am running into trouble when loading the ui-file dynamically when the program runs the loadUi() function. What throws me off is that the error occurs outside my script. Does that mean, I'm passing something wrong into it? Where does the error come in? Any hints on what could be wrong?
code_dir = os.path.dirname(os.path.abspath(__file__))
self.ui = loadUi(os.path.join(code_dir, "Ui_myfile.ui"), self)
This is the Error Code I am getting (minus the first paragraph):
File "C:/Dokumente und Einstellungen/name.name/.qgis/python/plugins\myfile\myfile_gui.py", line 42, in __ init __
self.ui = loadUi(os.path.join(code_dir, "Ui_myfile.ui"), self)
File "C:\PROGRA~1\QUANTU~1\apps\Python25\lib\site-packages\PyQt4\uic__init__.py", line 112, in loadUi
return DynamicUILoader().loadUi(uifile, baseinstance)
File "C:\PROGRA~1\QUANTU~1\apps\Python25\lib\site-packages\PyQt4\uic\Loader\loader.py", line 21, in loadUi
return self.parse(filename)
File "C:\PROGRA~1\QUANTU~1\apps\Python25\lib\site-packages\PyQt4\uic\uiparser.py", line 768, in parse
actor(elem)
File "C:\PROGRA~1\QUANTU~1\apps\Python25\lib\site-packages\PyQt4\uic\uiparser.py", line 616, in createUserInterface
self.traverseWidgetTree(elem)
File "C:\PROGRA~1\QUANTU~1\apps\Python25\lib\site-packages\PyQt4\uic\uiparser.py", line 594, in traverseWidgetTree
handler(self, child)
File "C:\PROGRA~1\QUANTU~1\apps\Python25\lib\site-packages\PyQt4\uic\uiparser.py", line 233, in createWidget
topwidget.setCentralWidget(widget)
SystemError: error return without exception set
I'm not sure of what could be causing this precise problem, but using .ui files directly has never worked well for me - instead I compile them to python code using pyuic4 (should be in your path if your PyQt4 site-packages are correctly configured. The syntax is along the lines of :-
pyuic4 -o <python output> -x <uic input>
-: resource files can similarly be converted to (not so human-readable) python using :-
pyrrc4 -o <python output> <qrc input>
-: You can then import that python file as a module, not to mention that reading its code can give you clues on how to fiddle with the layout at runtime.
The other upside of this is that you are not having to parse xml at runtime - importing a python module is far quicker and you are not likely to change the ui anywhere near as often as you run the script. If you do find yourself in this situation you can just create a batch to run these before your script/application.
This is the method I use in conjunction with pyInstaller to deploy scripts that will 'just run' on XP, Vista and Windows 7 without modification, and I generate the python modules just before compiling with pyInstaller, so it can be a real time saver.