How to load a raster layer using PyQGIS? - pyqt4

Although there are some posts on this matter, there is no answer in anyone of them. This is why I am asking it again.
One post I found was https://gis.stackexchange.com/questions/68032/raster-layer-invalid
I read information from the following link: https://hub.qgis.org/wiki/17/Arcgis_rest .
I used the command: gdal_translate "http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true" s.xml -of WMS. And it generated the file successfully. However, when I try to open the file and assuming the provider is wms, the code report layer is invalid.
The code I used is:
file = QFileDialog.getOpenFileName(self,
"Open WMS", ".", "WMS (*.xml)")
fileInfo = QFileInfo(file)
# Add the layer
layer = QgsRasterLayer(file, fileInfo.fileName(),"wms")
if not layer.isValid():
print "Failed to load."
return
I just choose the file from the dialog box.
I also tried the other command: qgis.utils.iface.addRasterLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true","raster") by using the following code:
layer = QgsRasterLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true", "layer")
if not layer.isValid():
print "Failed to load."
return
It also report "Failed to load". The original command can be run successfully in QGIS python command line. Also, if I try to enter the code in python console, the layer.isValid() would return true. It is just not working in standalone script.

Answer can be found here: https://gis.stackexchange.com/questions/120823/how-to-load-a-wms-layer-using-pyqgis.
Basically, it is just a version problem. If you have qgis previous than v2.6, it would not work. But it is fixed for 2.6
If it is still not working for you, you most likely have problem for environment variable settings.

This is working for me for single band image.I am using python 2.7 and QGIS 2.0.1 .You can load any raster layer like wms,tiff (single band or multiband) etc. using this.:
def ifile(self):
global fileName
fileName = str(QtGui.QFileDialog.getOpenFileName(self.iface.mainWindow(),"Open Raster File",'C:\\',"raster files(*.tif *.tiff *.TIF *.TIFF *.IMG *.img )"))
if len(fileName) is 0:
return
else:
self.inFileName = fileName;
filelayer = QgsRasterLayer(fileName,os.path.basename(fileName))
if filelayer == None or filelayer.bandCount() != 1:
self.errorMessage = "Not a DEM Image"
QMessageBox.information(self.iface.mainWindow(), "Error", self.errorMessage)
else:
#f=open(str(self.inFileName))
self.dlg.lineEdit.setText(self.inFileName)
if filelayer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(filelayer)
pass

Related

Python Tkinter Image saying 'no such file or directory'

I know many questions are out there on this but none of the solutions seem to have worked.
Here is my code:
image_1 = PhotoImage(file="AeolusPavillion_01"); image_1 = subsample(2)
backImg = Label(screen, image=image_1).place(x=50,y=50)
The error I get when this is run is
_tkinter.TclError: couldn't open "AeolusPavillion_01": no such file or directory
I have tried using tk.PhotoImage() and os.path. and using the actual path directory instead of the image name too but none of these have fixed it. e.g. c:/users/...
The image file is within the same folder as the python file and I made sure it was a .png file too as I heard JPEGs don't work in tkinter.
Has anyone got any solutions to what I could try next?
Just try doing
image_1 = PhotoImage(file="AeolusPavillion_01.jpg"); image_1 = subsample(2)
backImg = Label(screen, image=image_1).place(x=50,y=50)
or whatever file type it is

How to get WKHTMLTOPDF working on Heroku?

I created a website which generates PDF using PDFKIT and I know how to install and setup environment variable path on Window. I managed to deploy my first website on Heroku but now I'm getting error "No wkhtmltopdf executable found: "b''" When trying to generate the PDF.
I have no idea, How to install and setup WKHTMLTOPDF on Heroku because this is first time I'm dealing with Linux.
I really tried everything before asking this but even following this not working for me.
Python 3 flask install wkhtmltopdf on heroku
If possible, please guide me with step by step on how to install and setup this.
I followed all the resource and everything but couldn't make it work. Every time I get the same error.
I'm using Django version 2. Python version 3.7.
This is what I get if I do heroku stack
Available Stacks
cedar-14
container
heroku-16
* heroku-18
Error, I'm getting when generating the PDF.
No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf
My website works very well on localhost without any problem and as far as I know, I'm sure that I have done something wrong in installing wkhtmltopdf.
Thank you
It's non-trivial. If you want to avoid all of the below's headache, you can just use my service, api2pdf: https://github.com/api2pdf/api2pdf.python. Otherwise, if you want to try and work through it, see below.
1) Add this to your requirements.txt to install a special wkhtmltopdf pack for heroku as well as pdfkit.
git+git://github.com/johnfraney/wkhtmltopdf-pack.git
pdfkit==0.6.1
2) I created a pdf_manager.py in my flask app. In pdf_manager.py I have a method:
def _get_pdfkit_config():
"""wkhtmltopdf lives and functions differently depending on Windows or Linux. We
need to support both since we develop on windows but deploy on Heroku.
Returns:
A pdfkit configuration
"""
if platform.system() == 'Windows':
return pdfkit.configuration(wkhtmltopdf=os.environ.get('WKHTMLTOPDF_BINARY', 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'))
else:
WKHTMLTOPDF_CMD = subprocess.Popen(['which', os.environ.get('WKHTMLTOPDF_BINARY', 'wkhtmltopdf')], stdout=subprocess.PIPE).communicate()[0].strip()
return pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_CMD)
The reason I have the platform statement in there is that I develop on a windows machine and I have the local wkhtmltopdf binary on my PC. But when I deploy to Heroku, it runs in their linux containers so I need to detect first which platform we're on before running the binary.
3) Then I created two more methods - one to convert a url to pdf and another to convert raw html to pdf.
def make_pdf_from_url(url, options=None):
"""Produces a pdf from a website's url.
Args:
url (str): A valid url
options (dict, optional): for specifying pdf parameters like landscape
mode and margins
Returns:
pdf of the website
"""
return pdfkit.from_url(url, False, configuration=_get_pdfkit_config(), options=options)
def make_pdf_from_raw_html(html, options=None):
"""Produces a pdf from raw html.
Args:
html (str): Valid html
options (dict, optional): for specifying pdf parameters like landscape
mode and margins
Returns:
pdf of the supplied html
"""
return pdfkit.from_string(html, False, configuration=_get_pdfkit_config(), options=options)
I use these methods to convert to PDF.
Just follow these steps to Deploy Django app(pdfkit) on Heroku:
Step 1:: Add following packages in requirements.txt file
wkhtmltopdf-pack==0.12.3.0
pdfkit==0.6.0
Step 2: Add below lines in the views.py to add path of binary file
import os, sys, subprocess, platform
if platform.system() == "Windows":
pdfkit_config = pdfkit.configuration(wkhtmltopdf=os.environ.get('WKHTMLTOPDF_BINARY', 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'))
else:
os.environ['PATH'] += os.pathsep + os.path.dirname(sys.executable)
WKHTMLTOPDF_CMD = subprocess.Popen(['which', os.environ.get('WKHTMLTOPDF_BINARY', 'wkhtmltopdf')],
stdout=subprocess.PIPE).communicate()[0].strip()
pdfkit_config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_CMD)
Step 3: And then pass pdfkit_config as argument as below
pdf = pdfkit.from_string(html,False,options, configuration=pdfkit_config)

ValueError: Could not find a format to read the specified file in mode 'i'

I am trying to read a png file into a python-flask application running in docker and am getting an error that says
ValueError: Could not find a format to read the specified file in mode
'i'
i have uploaded a file using an HTML file and now i am trying to read it for further processing. i see that scipy.misc.imread is deprecated and i am trying to replace this with imageio.imread
if request.method=='POST':
file = request.files['image']
if not file:
return render_template('index.html', label="No file")
#img = misc.imread(file)
img = imageio.imread(file)
i get this error :
File "./appimclass.py", line 34, in make_prediction
img = imageio.imread(file)
File "/usr/local/lib/python3.6/site-packages/imageio/core/functions.py", line 221, in imread
reader = read(uri, format, "i", **kwargs)
File "/usr/local/lib/python3.6/site-packages/imageio/core/functions.py", line 139, in get_reader
"Could not find a format to read the specified file " "in mode %r" % mode
Different, but in case helpful. I had an identical error in a different library (skimage), and the solution was to add an extra 'plugin' parameter like so -
image = io.imread(filename,plugin='matplotlib')
Had the exact same problem recently, and the issue was a single corrupt file. Best is to use something like PIL to check for bad files.
import os
from os import listdir
from PIL import Image
dir_path = "/path/"
for filename in listdir(dir_path):
if filename.endswith('.jpg'):
try:
img = Image.open(dir_path+"\\"+filename) # open the image file
img.verify() # verify that it is, in fact an image
except (IOError, SyntaxError) as e:
print('Bad file:', filename)
#os.remove(dir_path+"\\"+filename) (Maybe)
I had this problem today, and found that if I closed the file before reading it into imageio the problem went away.
Error was:
File "/home/vinny/pvenvs/chess/lib/python3.6/site-packages/imageio/core/functions.py", line 139, in get_reader "Could not find a format to read the specified file " "in mode %r" % mode ValueError: Could not find a format to read the specified file in mode 'i'
Solution:
Put file.close() before images.append(imageio.imread(filename)), not after.
Add the option "pilmode":
imageio.imread(filename,pilmode="RGB")
It worked for me.
I encountered the same error, and at last, I found it was because the picture was damaged.
I had accidentally saved some images as PDF, so the error occurred. resolved after deleting those incompatible format images.

pyinstaller "could not parse stylesheet"

I'm building a small program using pyQt and pyInstaller.
I've tried to add an background image to my QMainWindow:
class pyPrimaMainWindow(QMainWindow):
def __init__(self):
...do some stuff...
self.setWindowIcon(QIcon(os.path.join(self.py_prima.resource_path(), "TH.ico"))) # <- this works
self.setStyleSheet("QMainWindow{{border-image: url({0});background-size:100%;}}".format(os.path.join(self.py_prima.resource_path(), "bg.png")))
The resource_path() methods looks like that:
def resource_path(self):
""" Get absolute path to resource, works for dev and for PyInstaller """
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = getattr(sys, '_MEIPASS', "C:/Users/Tobias/eclipse/workspace/PyPrima/data/")
# except Exception:
# base_path =
print(base_path)
return base_path
It's copied from the pyinstaller wiki, returns an absoulte path and works for other pictures/icons.
However, if I build an executable with pyInstaller, the programm runs nice, but the background image is missing. Instead, the console outputs
"could not parse stylesheet of object ..."
If I run the python file, it works all fine...
Any ideas on this?
Thanks!
I'll answer my own question just in case someone else stumbles upon the same problem.
The fileseparators are wrong...
Fix it with
bgpath = os.path.join(self.py_prima.resource_path(), "bg.png")
bgpath = bgpath.replace("\\", "/")
self.setStyleSheet("QMainWindow{{border-image: url({0});background-size: 100%;}}".format(
bgpath))

MATLAB MCC "??? Error Using ==> mcc, return status = 1"

I'm trying to compile a matlab .m file on a linux cluster using mcc. R2008b is installed on the cluster.
I am using http://www.it.northwestern.edu/research/sscc/matlabcompiler.html as a guide.
My plusone.m file is as follows:
function y = plusone(x)
if(ischar(x)), x = str2num(x), end;
y = x + 1;
I am running matlab on the cluster using the command "matlab -nodisplay".
I have run mbuild -setup and have added (my matlab root folder)/bin and /sbin to $PATH.
I am using the command mcc -m -v plusone.m from within MATLAB, and the full output is:
"??? Error using ==> mcc Error executing mcc, return status = 1."
This output is the same for a few different .m files and a number of different flag settings.
Without more error information, I'm a bit stumped. Suggestions about what might be causing the error or ways of getting more information about the error would be greatly appreciated.

Resources