I am trying to import nighttime light data on qgis and I keep getting invalid syntax at the last line of my code (Map. centerObject(sydney, 5))
Here is my code
import ee
from ee_plugin import Map
sydney_shp_path = ('Users/macbookpro/Downloads/OpenNightLights-master 2/onl/tutorials/files/city_of_sydney_shapefile')
night_img = ee.ImageCollection("NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG").filterDate('2018-01-01','2018-12-31').select('avg_rad')
NL_mean = night_img.mean()
nightclass = NL_mean.gt(5).add(NL_mean.gt(50)).add(NL_mean.gt(100))
nightclass = nightclass.updateMask(nightclass.neq(0))
Map.addLayer(nightclass.clip(sydney), ({'min':1, 'max':100}, 'VIIRS 2018', 'Nightlight')
Map.centerObject(sydney, 5)
Method Map.addLayer is not closed properly.
I am guessing method takes two parameters one return value of clip and another tuple.
Set center of map Map.setCentre()
Related
I'm trying to run a code that registers coordinates onto a heat map using Javascript on Jupyter Notebook. My code is:
import gmaps
import gmaps.datasets
gmaps.configure(api_key="MY API KEY")
data = [(-89.91161093276477, 35.241969778429194), (-89.87947624903887, 35.195319161704404), (-89.81418532101328, 35.17188216058175), (-89.75643652692003, 35.183538628834484), (-89.7496498284386, 35.14509890887518), (-89.78504762327763, 35.063349559432304), (-89.83100682136623, 35.013757847903044), (-89.85342496546569, 35.001086997562474)]
m = gmaps.Map()
heatmap_layer = gmaps.Heatmap(data=data)
m.add_layer(heatmap_layer)
m
But I keep on getting the error:
TraitError: The 'locations' trait of a Heatmap instance must be of length 1 <= L <= 9223372036854775807, but a value of [] was specified.
What does this mean and how can I fix it?
You are seeing this error because the function expects locations and you don't have anything defined there. I don't think you are calling your heatmap_layer correctly either.
https://jupyter-gmaps.readthedocs.io/en/latest/tutorial.html#heatmaps
Try this:
import gmaps.datasets
gmaps.configure(api_key="MY API KEY")
locations = [(-89.91161093276477, 35.241969778429194), (-89.87947624903887, 35.195319161704404), (-89.81418532101328, 35.17188216058175), (-89.75643652692003, 35.183538628834484), (-89.7496498284386, 35.14509890887518), (-89.78504762327763, 35.063349559432304), (-89.83100682136623, 35.013757847903044), (-89.85342496546569, 35.001086997562474)]
m = gmaps.Map()
heatmap_layer = gmaps.heatmap_layer(locations)
m.add_layer(heatmap_layer)
m
So I am trying to make a painterly node group with Python code straight so I can use it for future projects but I can't seem to get the power part of the formula in nuke to work from this colour difference formula( I'm also new to Nuke so if there is a better way of writing this please let me know it would be awesome thank you, or if I'm doing this wrong completely also let me know)
The following formula for color difference is used to create the
difference image: |(r1,g1,b1) – (r2,g2,b2)| = ((r1 – r2)^2 + (g1
–g2)^2 + (b1 – b2)^2)^1/2.
nRedShuffle = nuke.nodes.Shuffle()
nRedShuffle['red'].setValue('red')
nRedShuffle['green'].setValue('red')
nRedShuffle['blue'].setValue('red')
nRedShuffle['alpha'].setValue('red')
nGreenShuffle = nuke.nodes.Shuffle()
nGreenShuffle['red'].setValue('green')
nGreenShuffle['green'].setValue('green')
nGreenShuffle['blue'].setValue('green')
nGreenShuffle['alpha'].setValue('green')
#...(so on for the rest of rgba1 and rgba2)
nGreenShuffle2 = nuke.nodes.Shuffle()
nGreenShuffle2['red'].setValue('green')
nGreenShuffle2['green'].setValue('green')
nGreenShuffle2['blue'].setValue('green')
nGreenShuffle2['alpha'].setValue('green')
nBlueShuffle2 = nuke.nodes.Shuffle()
nBlueShuffle2['red'].setValue('blue')
nBlueShuffle2['green'].setValue('blue')
nBlueShuffle2['blue'].setValue('blue')
nBlueShuffle2['alpha'].setValue('blue')
#I am having troubles with the powers below
redDiff = nuke.nodes.Merge2(operation='minus', inputs=[nRedShuffle2, nRedShuffle])
redDiffMuli = nuke.nodes.Merge2(operation='multiply', inputs=[redDiff, redDiff])
greenDiff = nuke.nodes.Merge2(operation='minus', inputs=[nGreenShuffle2, nGreenShuffle])
greenDiffMuli = nuke.nodes.Merge2(operation='multiply', inputs=[greenDiff, greenDiff])
blueDiff = nuke.nodes.Merge2(operation='minus', inputs=[nBlueShuffle2, nBlueShuffle])
blueDiffMuli = nuke.nodes.Merge2(operation='multiply', inputs=[blueDiff, blueDiff])
redGreenAdd = nuke.nodes.Merge2(operation='plus', inputs=[redDiffMuli, greenDiffMuli])
redGreenBlueAdd = nuke.nodes.Merge2(operation='plus', inputs=[redGreenAdd, blueDiffMuli])
Here are at least two ways to implement Color Difference formula for two images. You can use difference op in Merge node or you can write a formula in field for each channel inside MergeExpression node:
Expression for each channel is as simple as this:
abs(Ar-Br)
abs(Ag-Bg)
abs(Ab-Bb)
Python commands
You can use .nodes.MergeExpression methodology:
import nuke
merge = nuke.nodes.MergeExpression(expr0='abs(Ar-Br)',
expr1='abs(Ag-Bg)',
expr2='abs(Ab-Bb)')
or regular .createNode syntax:
merge = nuke.createNode('MergeExpression')
merge['expr0'].setValue('abs(Ar-Br)')
merge['expr1'].setValue('abs(Ag-Bg)')
merge['expr2'].setValue('abs(Ab-Bb)')
Full code version
import nuke
import nukescripts
red = nuke.createNode("Constant")
red['color'].setValue([1,0,0,1])
merge = nuke.createNode('MergeExpression')
merge['expr0'].setValue('abs(Ar-Br)')
merge['expr1'].setValue('abs(Ag-Bg)')
merge['expr2'].setValue('abs(Ab-Bb)')
yellow = nuke.createNode("Constant")
yellow['color'].setValue([1,1,0,1])
merge.connectInput(0, yellow)
nuke.toNode('MergeExpression1').setSelected(True)
nukescripts.connect_selected_to_viewer(0)
# Auto-alignment in Node Graph
for everyNode in nuke.allNodes():
everyNode.autoplace()
Consider! MergeExpression node is much slower that regular Merge(difference) node.
I am a bit stuck trying to create driven (unitless) animCurves with OpenMaya
I am in maya 2017, using OpenMaya api 2.0
I am trying to use MFnAnimCurve to create multiple keyframes at the same time. this seems to work when using timed curve types (using MTimeArray as first argument) but it fails when using unitless curves and a MDoubleArray for the first argument..
Am I missing something? should i be using a different type for the first argument?
import maya.api.OpenMaya as om
import maya.api.OpenMayaAnim as oma
graph_modifier = om.MDGModifier()
m_object = om.MFnDependencyNode().create('transform', 'locator1')
node = om.MFnDependencyNode(m_object)
m_plug = node.findPlug(node.attribute('translateX'), True)
out_plug = node.findPlug(node.attribute('translateY'), True)
mfn_anim_curve = oma.MFnAnimCurve()
curve_type = mfn_anim_curve.unitlessAnimCurveTypeForPlug(m_plug)
#curve_type = mfn_anim_curve.timedAnimCurveTypeForPlug(m_plug)
anim_curve_m_object = oma.MFnAnimCurve().create(m_plug, animCurveType=curve_type)
anim_curve = oma.MFnAnimCurve(anim_curve_m_object)
in_plug = anim_curve.findPlug(anim_curve.attribute('input'), True)
graph_modifier.connect(out_plug, in_plug)
graph_modifier.doIt()
in_values = om.MDoubleArray()
out_values = om.MDoubleArray()
for x in range(5):
in_values.append(float(x))
for x in range(5):
out_values.append(float(x))
print in_values, out_values
anim_curve.addKey(1.0, 1.0)
anim_curve.addKey(2.0, 2.0)
#This Fails
anim_curve.addKeys(in_values, out_values)
Someone pointed out to me, That the documentation for MFnAnimCurve.addKeys() does specify that it only works for kAnimCurveTA, kAnimCurveTL, and kAnimCurveTU. Whereas the type being returned by unitlessAnimCurveTypeForPlug() is kAnimCurveUL
I have been stuck trying to do this with numpy with no luck. I am trying to move from MATLAB to Python, however, the transition hasn't been so easy. Anyway, that doesn't matter.
I am trying to code the Python analog of this simple MATLAB line of code:
A(:,:,condtype==1 & Mat(:,9)==contra(ii)) = A(:,:, condtype ==1 & Mat(:,9)==contra(ii))-mean(A(:,:, condtype ==1 & Mat(:,9)==contra(ii)),3);
Right, so the above convoluted line of code does the following. Indexes a condition which is half of the 3rd dimension of A and removes the mean of those indexes which simultaneously changing the values in A to the new mean removed values.
How would one go about doing this in Python?
I actually figured it out. I was trying to use and when I should have been using np.isequal. Also, I needed to use keepdims=True for the mean. Here it is for anyone that wants to see:
def RmContrastMean(targettype,trialsMat,Contrastlvls,dX):
present = targettype==1
absent = targettype==0
for i in range(0,Contrastlvls.size):
CurrentContrast = trialsMat[:,8]==Contrastlvls[i]
preIdx = np.equal(present, CurrentContrast)
absIdx = np.equal(absent, CurrentContrast)
#mean
dX[:,:,preIdx] = dX[:,:,preIdx]-np.mean(dX[:,:,preIdx],axis=2,keepdims=True)
dX[:,:,absIdx] = dX[:,:,absIdx]-np.mean(dX[:,:,absIdx],axis=2,keepdims=True)
#std
dX[:,:,preIdx] = dX[:,:,preIdx]/np.std(dX[:,:,preIdx],axis=2,keepdims=True)
dX[:,:,absIdx] = dX[:,:,absIdx]/np.std(dX[:,:,absIdx],axis=2,keepdims=True)
return dX
I am new to google earth engine and was trying to understand how to use the Google Earth Engine python api. I can create an image collection, but apparently the getdownloadurl() method operates only on individual images. So I am trying to understand how to iterate over and download all of the images in the collection.
Here is my basic code. I broke it out in great detail for some other work I am doing.
import ee
ee.Initialize()
col = ee.ImageCollection('LANDSAT/LC08/C01/T1')
col.filterDate('1/1/2015', '4/30/2015')
pt = ee.Geometry.Point([-2.40986111110000012, 26.76033333330000019])
buff = pt.buffer(300)
region = ee.Feature.bounds(buff)
col.filterBounds(region)
So I pulled the Landsat collection, filtered by date and a buffer geometry. So I should have something like 7-8 images in the collection (with all bands).
However, I could not seem to get iteration to work over the collection.
for example:
for i in col:
print(i)
The error indicates TypeError: 'ImageCollection' object is not iterable
So if the collection is not iterable, how can I access the individual images?
Once I have an image, I should be able to use the usual
path = col[i].getDownloadUrl({
'scale': 30,
'crs': 'EPSG:4326',
'region': region
})
It's a good idea to use ee.batch.Export for this. Also, it's good practice to avoid mixing client and server functions (reference). For that reason, a for-loop can be used, since Export is a client function. Here's a simple example to get you started:
import ee
ee.Initialize()
rectangle = ee.Geometry.Rectangle([-1, -1, 1, 1])
sillyCollection = ee.ImageCollection([ee.Image(1), ee.Image(2), ee.Image(3)])
# This is OK for small collections
collectionList = sillyCollection.toList(sillyCollection.size())
collectionSize = collectionList.size().getInfo()
for i in xrange(collectionSize):
ee.batch.Export.image.toDrive(
image = ee.Image(collectionList.get(i)).clip(rectangle),
fileNamePrefix = 'foo' + str(i + 1),
dimensions = '128x128').start()
Note that converting a collection to a list in this manner is also dangerous for large collections (reference). However, this is probably the most scalable method if you really need to download.
Here is my solution:
import ee
ee.Initialize()
pt = ee.Geometry.Point([-2.40986111110000012, 26.76033333330000019])
region = pt.buffer(10)
col = ee.ImageCollection('LANDSAT/LC08/C01/T1')\
.filterDate('2015-01-01','2015-04-30')\
.filterBounds(region)
bands = ['B4','B5'] #Change it!
def accumulate(image,img):
name_image = image.get('system:index')
image = image.select([0],[name_image])
cumm = ee.Image(img).addBands(image)
return cumm
for band in bands:
col_band = col.map(lambda img: img.select(band)\
.set('system:time_start', img.get('system:time_start'))\
.set('system:index', img.get('system:index')))
# ImageCollection to List
col_list = col_band.toList(col_band.size())
# Define the initial value for iterate.
base = ee.Image(col_list.get(0))
base_name = base.get('system:index')
base = base.select([0], [base_name])
# Eliminate the image 'base'.
new_col = ee.ImageCollection(col_list.splice(0,1))
img_cummulative = ee.Image(new_col.iterate(accumulate,base))
task = ee.batch.Export.image.toDrive(
image = img_cummulative.clip(region),
folder = 'landsat',
fileNamePrefix = band,
scale = 30).start()
print('Export Image '+ band+ ' was submitted, please wait ...')
img_cummulative.bandNames().getInfo()
A reproducible example can you found it here: https://colab.research.google.com/drive/1Nv8-l20l82nIQ946WR1iOkr-4b_QhISu
You could possibly use ee.ImageCollection.iterate() with a function that gets the image and adds it to a list.
import ee
def accumluate_images(image, images):
images.append(image)
return images
for img in col.iterate(accumulate_images, []):
url = img.getDownloadURL(dict(scale=30, crs='EPSG:4326', region=region))
Unfortunately I am not able to test this code as I do not have access to the API, but it might help you arrive at a solution.
I have a similar problem and was not able o solve with presented solutions. Then I have elaborated a sample code for this purpose. It iterates over an image collection in client side, then it is not affected by limitations (server side only) of .map() or .iterate().
It is possible to download the code and see its explanation here
It basically transform the ImageCollection into a list (ic.toList()). Then it performs a standard loop, and for each individual image it is possible to convert it back to ee.Image(list.get(i)), and then process one by one taking all images in the collection.
In your particular case, to download each image, the function to be called within the loop could be: getDOwnloadURL() or getThumbURL():
var url = imgNew.getDownloadURL({
region: geometry,
});
var thumbURL = imgNew.getThumbURL({region: geometry,dimensions: 512, format: 'png'});