Convert raster into shapefile with attributes - python

I made this code in python 2.7 for downloading bing traffic flow map (specific area) every x minutes.
from cStringIO import StringIO
from PIL import Image
import urllib
import time
i = 1
end = time.time() + 60*24*60
url = 'https://dev.virtualearth.net/REST/V1/Imagery/Map/AerialWithLabels/45.8077453%2C15.963863/17?mapSize=500,500&mapLayer=TrafficFlow&format=png&key=Lt2cLlR9OcfEnMLv5qyd~YbPpC6zOQdhTMcwsKCwlgQ~Am2YLG00hHI6h7W1IPq31VOzqEXKAhedzHfknCejIrdQF_iVrQS82AUdjBT0YMtt'
while True:
buffer = StringIO(urllib.urlopen(url).read())
image = Image.open(buffer)
image.save('C:\Users\slika'+str(i)+'.png')
i=i+1
if time.time()>end:
break
time.sleep(60*10)
This is one of the images i got traffic flow
Now my question is can i convert only traffic flow lines (green,yellow, orange, red) and assign them attributes (1,2,3,4) or ('No traffic' , 'Light' , 'Moderate' , 'Heavy') into shape file for usage in QGIS. What modules should i look for and is it even possible. Any idea or sample code would be much helpful.

This is against the terms of use of Bing Maps.
Also, I notice that you are using a Universal Windows App key. Those keys are to only be used in public facing Windows apps that anyone has access to. These keys cannot be used in GIS/business apps. Use a Dev/Test key or upgrade to an Enterprise account.

Related

Saving area within a shape (rectangle) as image from multiple powerpoint slides

I'm attempting to grab an image of diagrams constructed within a rectangle on a power point slide deck. I found python-pptx and am able to identify the shapes on each slide. Is there any way to expand this to take a snapshot of the area within the rectangle shape and export it as an image?
# Auto grab the photos created in Powerpoint
from pptx import Presentation
prs = Presentation('ex.pptx')
for slide in prs.slides:
print(slide)
for shape in slide.shapes:
print(shape)
# Identify shape on each slide, find area within, and save as .png
I think you're going to be best off looking at a COM32 type of solution, either writing something in VBA or possibly using the win32com library in Python if you really want a Python solution.
Either way this is going to fire up a "live" PowerPoint application instance and basically run it by remote control. That sort of thing isn't a great idea server-side, but if it's just for personal productivity it might work fine.
python-pptx can't do this sort of thing and probably never will. The rendering engine needs to get involved in this type of work and python-pptx is strictly a .pptx file editor/generator.
With Aspose.Slides for Python, you can easily save presentation shapes to images. The following code example shows you how to save all charts from a presentation to PNG images:
import aspose.slides as slides
import aspose.slides.charts as charts
import aspose.pydrawing as draw
with slides.Presentation("example.pptx") as presentation:
for slide_index, slide in enumerate(presentation.slides):
for shape_index, shape in enumerate(slide.shapes):
# Looking for charts, for example.
if isinstance(shape, charts.Chart):
# Get a chart image.
with shape.get_thumbnail() as chart_image:
# Save the chart image to PNG.
image_path = "chart_image_{}_{}.png".format(slide_index, shape_index)
chart_image.save(image_path, draw.imaging.ImageFormat.png)
Aspose.Slides for Python is a paid product, but you can get a temporary license or use it in a trial mode to evaluate all features for managing presentations. Alternatively, you can use Aspose.Slides Cloud SDK for Python. This package provides a REST-based API for managing presentations as well. The code example below shows you how to do the same using Aspose.Slides Cloud:
import asposeslidescloud
import aspose.pydrawing as draw
from asposeslidescloud.apis.slides_api import SlidesApi
from asposeslidescloud.models import *
slides_api = SlidesApi(None, "my_client_id", "my_client_secret")
file_name = "example.pptx"
# Upload the presentation to the default storage.
with open(file_name, "rb") as file_stream:
slides_api.upload_file(file_name, file_stream)
# Get the number of slides.
slides_info = slides_api.get_slides(file_name)
slide_count = len(slides_info.slide_list)
for slide_index in range(1, slide_count + 1):
# Get the number of shapes on the current slide.
shapes_info = slides_api.get_shapes(file_name, slide_index)
shape_count = len(shapes_info.shapes_links)
for shape_index in range(1, shape_count + 1):
shape = slides_api.get_shape(file_name, slide_index, shape_index)
# Looking for charts, for example.
if shape.type == "Chart":
# Get the chart as a PNG image.
image_path = slides_api.download_shape(file_name, slide_index, shape_index, ShapeExportFormat.PNG)
print("A chart image was saved to " + image_path)
This is also a paid product, but you can make 150 free API calls per month for any purposes.
I work as a Support Developer at Aspose and can answer your questions of these libraries on Aspose.Slides forum.

Convert PNG to ZPL and print

I'm trying to convert an image to ZPl and then print the label to a 6.5*4cm label on a TLP 2844 zebra printer on Python.
My main problems are:
1.Converting the image
2.Printing from python to the zebra queue (I've honestly tried all the obvious printing packages like zebra0.5/ win32 print/ ZPL...)
Any help would be appreciated.
I had the same issue some weeks ago. I made a python script specifically for this printer, with some fields available. I commented (#) what does not involve your need, but left it in as you may find it helpful.
I also recommend that you set your printer to the EPL2 driver, and 5cm/s print speed. With this script you'll get the PNG previews with an EAN13 formatted barcode. (If you need other formats, you might need to hit the ZPL module docs.)
Please bear in mind that if you print with ZLP 2844, you will either need to use their paid software, or you will need to manually configure the whole printer.
import os
import zpl
#import pandas
#df= pandas.read_excel("Datos.xlsx")
#a=pandas.Series(df.GTIN.values,index=df.FINAL).to_dict()
for elem in a:
l = zpl.Label(15,25.5)
height = 0
l.origin(3,1)
l.write_text("CUIT: 30-11111111-7", char_height=2, char_width=2, line_width=40)
l.endorigin()
l.origin(2,5)
l.write_text("Art:", char_height=2, char_width=2, line_width=40)
l.endorigin()
l.origin(5.5,4)
l.write_text(elem, char_height=3, char_width=2.5, line_width=40)
l.endorigin()
l.origin(2, 7)
l.write_barcode(height=40, barcode_type='2', check_digit='N')
l.write_text(a[elem])
l.endorigin()
height += 8
l.origin(8.5, 13)
l.write_text('WILL S.A.', char_height=2, char_width=2, line_width=40)
l.endorigin()
print(l.dumpZPL())
lista.append(l.dumpZPL())
l.preview()
To print the previews without having to watch and confirm each preview, I ended up modifying the ZPL preview method, to return an IO variable so I can save it to a file.
fake_file = io.BytesIO(l.preview())
img = Image.open(fake_file)
img = img.save('tags/'+'name'+'.png')
On the Label.py from ZPL module (preview method):
#Image.open(io.BytesIO(res)).show(). <---- comment out the show, but add the return of the BytesIO
return res
I had similar issues and created a .net core application which takes an image and converts it to ZPL, either to a file or to the console so it's pipeable in bash scripts. You could package it with your python app call it as a subprocess like so:
output = subprocess.Popen(["zplify", "path/to/file.png"], stdout=subprocess.PIPE).communicate()[0]
Or feel free to use my code as a reference point and implement it in python.
Once you have a zpl file or stream you can send it directly to a printer using lpr if you're on linux. If on windows you can connect to a printer using it's IP address as shown in this stack overflow question
For what is worth and for anyone else reference, was facing a similar situation and came up with a solution. To whom it may help:
Converting the image?
After trying many libraries i came across ZPLGRF although it seems the demo is focused on PDF only, i found in the source that there is a from_image() class property that could convert from image to zpl combining it part of the demo/exaples. Full code description below
Printing from python to the zebra queue?
Many libraries again but i settled with ZEBRA seem to be the most straight forward one to send raw zpl to a zebra printer
CODE
from zplgrf import GRF
from zebra import Zebra
#Open the image file and generate ZPL from it
with open(path_to_your_image, 'rb') as img:
grf = GRF.from_image(img.read(), 'LABEL')
grf.optimise_barcodes()
zpl_code = grf.to_zpl
#Setup and print to Zebra Printer
z = Zebra()
#This will return a list of all the printers on a given machine as a list
#['printer1', 'printer2', ...]
z.getqueues()
#If or once u know the printer queue name then u can set it up with
z.setqueue('printer1')
#And now is ready to send the raw ZPL text
z.output(zpl_code )
The above i have tested successfully with a Zebra GX430t printer connected via USB in a Windows 11 machine.
Hope it helps

Embedding Google Earth with Python

Is there a way to embed Google Earth or Google Earth Engine in a Python desktop application?
As of now, I've created a kml file with longitude/latitude data that can be manually dropped into Google Earth Pro to trace the path of the GPS.
I've seen a lot of forum posts where Google Earth was embedded in webpages but not desktop applications so I was wondering if it could be done.
Any suggestions would be appreciated
Yes, you can add Google Earth Engine results to a desktop application as long as it supports WMS tile layers, images, or graphs.
Here are some examples assuming your have already gone through these preprocesing steps:
import ee
ee.Initialize() # note: may have initialize with a service account within an application
# ee Image object of the Global SRTM data
img = ee.Image("USGS/SRTMGL1_003")
Get WMS tiles:
# get map tile id and token with specific color palette
# arguments into "getMapId" are the same as the JavaScript API "Map.addLayer"
result = img.getMapId({'min': 0, 'max': 3000})
url = "https://earthengine.googleapis.com/map/{mapid}/{{z}}/{{x}}/{{y}}?token={token}"
tiles = url.format(**result)
print(tiles)
# visualize in your favorite application that supports WMS
Get static Image:
# Generate a URL that displays a static Image from Global DEM
url = img.getThumbUrl({'min':0, 'max':3000})
# create a file-like object from the url
import urllib2
f = urllib2.ulropen(url)
# Display the image using matplotlib
import matplotlib.pyplot as plt
result = plt.imread(f)
plt.imshow(result)
plt.show()
Displaying a time series graph may be a little more involved:
# get a collection with time series
collection = ee.ImageCollection('MODIS/006/MOD11A2')\
.filterDate('2016-01-01','2018-01-01')
# create a geometry of area to show time series
atl = ee.Geometry.Point([-84.3880,33.7490])
# get a time series over the point
result = collection.select('LST_Day_1km').getRegion(atl,1000).getInfo()
# turn the result into a pandas dataframe and manipulate results for plotting
import pandas as pd
df = pd.DataFrame(result[1:])
df.columns = result[0]
# convert epoch time to a format for pandas
dates = [pd.Timestamp(t*1000000) for t in df.time]
# make new pandas series object with scaled LST values
ts = pd.Series(np.array(df.LST_Day_1km)*0.02-273.15,index=dates,name='lst')
ts.index.name = 'Date'
# finally display results
ts.plot()
There are probably more efficient ways to get the results and display in an application, however, this may be a way to get you started.
Two second google search found this! So in answer to your question, yes you can use Google Earth in Python
https://developers.google.com/earth-engine/python_install

Why GCP Vision API returns worse results in python than at its online demo

I wrote a basic python script to call and use the GCP Vision API. My aim is to send an image of a product to it and to retrieve (with OCR) the words written on this box. I have a predefined list of brands so I can search within the returned text from the API the brand and detect what it is.
My python script is the following:
import io
from google.cloud import vision
from google.cloud.vision import types
import os
import cv2
import numpy as np
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "**************************"
def detect_text(file):
"""Detects text in the file."""
client = vision.ImageAnnotatorClient()
with io.open(file, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
print('Texts:')
for text in texts:
print('\n"{}"'.format(text.description))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in text.bounding_poly.vertices])
print('bounds: {}'.format(','.join(vertices)))
file_name = "Image.jpg"
img = cv2.imread(file_name)
detect_text(file_name)
For now, I am experimenting with the following product image: (951 × 335 resolution)
Its brand is Acuvue.
The problem is the following. When I am testing the online demo of GCP Cloud Vision API then I am getting the following text result for this image:
FOR ASTIGMATISM 1-DAY ACUVUE MOIST WITH LACREON™ 30 Lenses BRAND CONTACT LENSES UV BLOCKING
(The json result for this returns all the above words including the word Acuvue which matters for me but the json is too long to post it here)
Therefore, the online demo detects pretty well the text on the product and at least it detects accurately the word Acuvue (which is the brand). However, when I am calling the same API in my python script with the same image I am getting the following result:
Texts:
"1.DAY
FOR ASTIGMATISM
WITH
LACREONTM
MOIS
30 Lenses
BRAND CONTACT LENSES
UV BLOCKING
"
bounds: (221,101),(887,101),(887,284),(221,284)
"1.DAY"
bounds: (221,101),(312,101),(312,125),(221,125)
"FOR"
bounds: (622,107),(657,107),(657,119),(622,119)
"ASTIGMATISM"
bounds: (664,107),(788,107),(788,119),(664,119)
"WITH"
bounds: (614,136),(647,136),(647,145),(614,145)
"LACREONTM"
bounds: (600,151),(711,146),(712,161),(601,166)
"MOIS"
bounds: (378,162),(525,153),(528,200),(381,209)
"30"
bounds: (614,177),(629,178),(629,188),(614,187)
"Lenses"
bounds: (634,178),(677,180),(677,189),(634,187)
"BRAND"
bounds: (361,210),(418,210),(418,218),(361,218)
"CONTACT"
bounds: (427,209),(505,209),(505,218),(427,218)
"LENSES"
bounds: (514,209),(576,209),(576,218),(514,218)
"UV"
bounds: (805,274),(823,274),(823,284),(805,284)
"BLOCKING"
bounds: (827,276),(887,276),(887,284),(827,284)
But this does not detect at all the word "Acuvue" as the demo does!!
Why is this happening?
Can I fix something in my python script to make it work properly?
From the docs:
The Vision API can detect and extract text from images. There are two annotation features that support OCR:
TEXT_DETECTION detects and extracts text from any image. For example, a photograph might contain a street sign or traffic sign. The JSON includes the entire extracted string, as well as individual words, and their bounding boxes.
DOCUMENT_TEXT_DETECTION also extracts text from an image, but the response is optimized for dense text and documents. The JSON includes page, block, paragraph, word, and break information.)
My hope was that the web API was actually using the latter, and then filtering the results based on the confidence.
A DOCUMENT_TEXT_DETECTION response includes additional layout information, such as page, block, paragraph, word, and break information, along with confidence scores for each.
At any rate, I was hoping (and my experience has been) that the latter method would "try harder" to find all the strings.
I don't think you were doing anything "wrong". There are just two parallel detection methods. One (DOCUMENT_TEXT_DETECTION) is more intense, optimized for documents (likely for straightened, aligned and evenly spaced lines), and gives more information that might be unnecessary for some applications.
So I suggested you modify your code following the Python example here.
Lastly, my guess is that the \342\204\242 you ask about are escaped octal values corresponding to utf-8 characters it thinks it found when trying to identify the ™ symbol.
If you use the following snippet:
b = b"\342\204\242"
s = b.decode('utf8')
print(s)
You'll be happy to see that it prints ™.

Can python-pptx module insert video?

according to the documentation, python-pptx can insert videos, however, the documentation does not give very good examples. Anybody have any code snippets to add video1.avi to my pptx?
from pptx import Presentation
pptx1 = Presentation()
slide = pptx1.slides.add_slide(blank_slide_layout)
not sure what inputs I need
slide.placeholders.element.add_placeholder(id_,name,ph_type, orient, sz,idx)
thanks
UPDATE: python-pptx now supports inserting videos (and probably audio in many cases using the same method).
I'm not sure where in the documentation it says it can insert videos, but if you can cite a particular location I'll fix it.
We've looked at this feature, but it turns out to be quite complex as different video formats require a substantial amount of undocumented customization to the metadata inserted into the XML surrounding the embedded video object. Also as I recall one needs a way to get a still image (first frame maybe) from the video to insert in it's place while it's not running, and libraries for this sort of thing are not readily available in Python last time we looked.
Anyway, the short answer is no, it's not supported yet. And it's not likely to come soon unless there's a motivated contributor or sponsor. Sorry I didn't have happier news for you :(
I ended up converting my avi video to an animated gif, and that successfully inserted into the pptx
aviname = 'vid1.avi'
from moviepy.editor import VideoFileClip
aviname = 'vid1.avi'
clip = VideoFileClip(aviname)
clip.write_gif(os.path.splitext(aviname)[0]+'.gif')
The library now has a function for adding videos to slides:
slide.shapes.add_movie(video_file, x_pos, y_pos, width, height, poster_frame_image=thumbnail_image_file)
this video could help you:
https://www.youtube.com/watch?v=5a1kH996DJM&t=315s
he speaks arabic. Here is the code:
import pptx
from pptx.utils import Cm
from pptx.enum.shapes import PP_MEDIA_TYPE
pres = pptx.Presentation()
blank_slide = pres.slides.add_slide(pres.slide_layouts[6])
movie_path = "path"
movie_shape = blank_slide.shapes.add_movie(left = Cm(5), top = Cm(5), width = Cm(10), height = Cm(10), poster_frame_image = "image_path", mime_type = "video/mp4")
movie_shape.media_type = PP_MEDIA_TYPE.MOVIE
pres.save("pres.pptx")

Categories