Skip to content

Instantly share code, notes, and snippets.

@BibMartin
Created September 1, 2021 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BibMartin/f538d656d44ee6c938ccde3af936b809 to your computer and use it in GitHub Desktop.
Save BibMartin/f538d656d44ee6c938ccde3af936b809 to your computer and use it in GitHub Desktop.
A folium element transform the tiles into grayscale (based on https://github.com/Zverik/leaflet-grayscale/)
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
import folium
from jinja2 import Template
class GrayScaleTiles(folium.MacroElement):
"""Add this element to your map in order to have grayscale tiles.
Based on https://github.com/Zverik/leaflet-grayscale/
"""
_name = "GrayScaleTiles"
_template = Template("""
{% macro header(this, kwargs) %}
<script>
/*
* L.TileLayer.Grayscale is a regular tilelayer with grayscale makeover.
*/
L.TileLayer.Grayscale = L.TileLayer.extend({
options: {
quotaRed: 21,
quotaGreen: 71,
quotaBlue: 8,
quotaDividerTune: 0,
quotaDivider: function() {
return this.quotaRed + this.quotaGreen + this.quotaBlue + this.quotaDividerTune;
}
},
initialize: function (url, options) {
options = options || {}
options.crossOrigin = true;
L.TileLayer.prototype.initialize.call(this, url, options);
this.on('tileload', function(e) {
this._makeGrayscale(e.tile);
});
},
_createTile: function () {
var tile = L.TileLayer.prototype._createTile.call(this);
tile.crossOrigin = "Anonymous";
return tile;
},
_makeGrayscale: function (img) {
if (img.getAttribute('data-grayscaled'))
return;
img.crossOrigin = '';
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var imgd = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i] = pix[i + 1] = pix[i + 2] = (this.options.quotaRed * pix[i] + this.options.quotaGreen * pix[i + 1] + this.options.quotaBlue * pix[i + 2]) / this.options.quotaDivider();
}
ctx.putImageData(imgd, 0, 0);
img.setAttribute('data-grayscaled', true);
img.src = canvas.toDataURL();
}
});
L.tileLayer = function (url, options) {
return new L.TileLayer.Grayscale(url, options);
};
</script>
{% endmacro %}
""")
m = folium.Map([45,0], tiles='OpenStreetMap', zoom_start=4).add_child(GrayScaleTiles())
m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment