Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8839743
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T10:18:24+00:00 2026-06-14T10:18:24+00:00

I have a raster image (in Tiff format) and a polygon area in shapefile

  • 0

I have a raster image (in Tiff format) and a polygon area in shapefile format converted in an Array. I wish to find an elegant way to create an array where all element inside the border of polygon have 1 value and all element outside the polygon have value 0. My final goal is mask the array derived from the image with the array derived from the shapefile.

i have the following question and thanks for helps:

after create an empty array using np.zeros((ds.RasterYSize, ds.RasterXSize)) and the pixel location of a geospatial coordinate of the border of my polygon, what is the best solution to fill with 1 the polygon inside the array?

from osgeo import gdal, gdalnumeric, ogr, osr
import osgeo.gdal
import math
import numpy
import numpy as np

def world2Pixel(geoMatrix, x, y):
    """
    Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
    the pixel location of a geospatial coordinate
    (source http://www2.geog.ucl.ac.uk/~plewis/geogg122/vectorMask.html)
    geoMatrix
    [0] = top left x (x Origin)
    [1] = w-e pixel resolution (pixel Width)
    [2] = rotation, 0 if image is "north up"
    [3] = top left y (y Origin)
    [4] = rotation, 0 if image is "north up"
    [5] = n-s pixel resolution (pixel Height)

    """
    ulX = geoMatrix[0]
    ulY = geoMatrix[3]
    xDist = geoMatrix[1]
    yDist = geoMatrix[5]
    rtnX = geoMatrix[2]
    rtnY = geoMatrix[4]
    pixel = np.round((x - ulX) / xDist).astype(np.int)
    line = np.round((ulY - y) / xDist).astype(np.int)
    return (pixel, line)

# Open the image as a read only image
ds = osgeo.gdal.Open(inFile,gdal.GA_ReadOnly)
# Get image georeferencing information.
geoMatrix = ds.GetGeoTransform()
ulX = geoMatrix[0] # top left x (x Origin)
ulY = geoMatrix[3] # top left y (y Origin)
xDist = geoMatrix[1] # w-e pixel resolution (pixel Width)
yDist = geoMatrix[5] # n-s pixel resolution (pixel Height)
rtnX = geoMatrix[2] # rotation, 0 if image is "north up"
rtnY = geoMatrix[4] #rotation, 0 if image is "north up"

# open shapefile (= border of are of interest)
shp = osgeo.ogr.Open(poly)
source_shp = ogr.GetDriverByName("Memory").CopyDataSource(shp, "")
# get the coordinates of the points from the boundary of the shapefile
source_layer = source_shp.GetLayer(0)
feature = source_layer.GetNextFeature()
geometry = feature.GetGeometryRef()
pts = geometry.GetGeometryRef(0)
points = []
for p in range(pts.GetPointCount()):
   points.append((pts.GetX(p), pts.GetY(p)))
pnts = np.array(points).transpose()

print pnts
pnts
array([[  558470.28969598,   559495.31976318,   559548.50931402,
    559362.85560495,   559493.99688721,   558958.22572622,
    558529.58862305,   558575.0174293 ,   558470.28969598],
    [ 6362598.63707171,  6362629.15167236,  6362295.16466266,
    6362022.63453845,  6361763.96246338,  6361635.8559779 ,
    6361707.07684326,  6362279.69352024,  6362598.63707171]])

# calculate the pixel location of a geospatial coordinate (= define the border of my polygon)

pixels, line = world2Pixel(geoMatrix,pnts[0],pnts[1])
pixels
array([17963, 20013, 20119, 19748, 20010, 18939, 18081, 18172, 17963])
line
array([35796, 35734, 36402, 36948, 37465, 37721, 37579, 36433, 35796])

#create an empty array with value zero using 
data = np.zeros((ds.RasterYSize, ds.RasterXSize))
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T10:18:25+00:00Added an answer on June 14, 2026 at 10:18 am

    This is essentially a point-in-polygon problem.

    Here’s a little library to solve this problem. It’s from this page with some modifications to make it more readable.

    pip.py

    #From http://www.ariel.com.au/a/python-point-int-poly.html
    # Modified by Nick ODell
    from collections import namedtuple
    
    def point_in_polygon(target, poly):
        """x,y is the point to test. poly is a list of tuples comprising the polygon."""
        point = namedtuple("Point", ("x", "y"))
        line = namedtuple("Line", ("p1", "p2"))
        target = point(*target)
    
        inside = False
        # Build list of coordinate pairs
        # First, turn it into named tuples
    
        poly = map(lambda p: point(*p), poly)
    
        # Make two lists, with list2 shifted forward by one and wrapped around
        list1 = poly
        list2 = poly[1:] + [poly[0]]
        poly = map(line, list1, list2)
    
        for l in poly:
            p1 = l.p1
            p2 = l.p2
    
            if p1.y == p2.y:
                # This line is horizontal and thus not relevant.
                continue
            if max(p1.y, p2.y) < target.y <= min(p1.y, p2.y):
                # This line is too high or low
                continue
            if target.x < max(p1.x, p2.x):
                # Ignore this line because it's to the right of our point
                continue
            # Now, the line still might be to the right of our target point, but 
            # still to the right of one of the line endpoints.
            rise = p1.y - p2.y
            run =  p1.x - p2.x
            try:
                slope = rise/float(run)
            except ZeroDivisionError:
                slope = float('inf')
    
            # Find the x-intercept, that is, the place where the line we are
            # testing equals the y value of our target point.
    
            # Pick one of the line points, and figure out what the run between it
            # and the target point is.
            run_to_intercept = target.x - p1.x
            x_intercept = p1.x + run_to_intercept / slope
            if target.x < x_intercept:
                # We almost crossed the line.
                continue
    
            inside = not inside
    
        return inside
    
    if __name__ == "__main__":
        poly = [(2,2), (1,-1), (-1,-1), (-1, 1)]
        print point_in_polygon((1.5, 0), poly)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a raster file (basically 2D array) with close to a million points.
I have to save my FrameworkElement as very large raster image. For now I
My input raster consists of multiple layers, each with an image area surrounded by
I have a map that I converted from a raster graphic into an SVG
Suppose we have 20x20 raster image. How does zooming work? For instance how to
I have raster table in postgresql that I create it using PostGIS raster. If
I have a game with a big raster map Now we are using jpeg
have a problem. At first look at this HTML <div id=map style=background-image: url(map.png); width:
I need to create a grayscale image from data in an nio ShortBuffer. I
I have a flat white circular image (as in a seriously flat #ffffff image).

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.