I want to filter shapefiles by their latitude behaviour: If the latitudes of edges A and B are constantly decreasing or increasing then this class marked as correct, otherwise are incorrect. For example, the red polygon should be marked as incorrect! (Because it starts increasing at the point C.)

enter image description here

This code works but selects also some correct shapefiles (because I set an absolute value for checking the latitude. This behaviour appears in north and south).

Does someone know how can I detect this kind of shapefile?


import shapefile
import numpy as np

sf = shapefile.Reader(r"shapefiles/shapefiles.shp")
of = r"_temp/error.txt"

shapes = sf.shapeRecords()
ids = np.zeros(len(shapes))

output = open(of, 'w')
output = open(of, 'a')
for shp in shapes:
    lats = np.zeros(len(shp.shape.points))
    lons = np.zeros(len(shp.shape.points))
    for i in range(0, len(shp.shape.points)):
        point = shp.shape.points[i]
        lats[i] = (point[1])
        lons[i] = (point[0])
    if max(lats)>86.5:
        #print shp.record[0]
    if min(lats)<-79.2:
        #print shp.record[0]

    # identification of shapefiles crossing dateline - not needed here
    #if max(lons)>179.9: continue
    #if min(lons)<-179.9: continue
  • 1
    Couldn't you simply compare 3 consecutive points (moving window) to detect if the delta in x- and y-component is increasing or decreasing? You have to pick the 1st and 2nd point before the for i in range() loop and do comparison and assignment of new values in the loop.
    – Detlev
    Commented Jan 30, 2016 at 12:29
  • 1
    You've got a bunch of complications here, including: The first vertex can occur anywhere, the shapefile may be topologically corrupt (not follow right-hand rule), and a loop can't always increase or decrease in one dimension. Since every shape has an envelope, you can identify the northeast-most point and use that neighborhood for analysis, but the result will only be correct if the topology is correct.
    – Vince
    Commented Jan 30, 2016 at 13:38
  • 1
    Is that code meant to do anything apart from read the data?
    – Spacedman
    Commented Jan 30, 2016 at 13:39
  • 1
    I think if you loop over the points going round the polygon and count the number of times the sign of the difference in latitude between point i and i+1 changes. The polygons you want change sign four times, the ones you don't want change more than that.
    – Spacedman
    Commented Jan 30, 2016 at 13:41
  • 2
    @Tom oops yes twice. you only need the latitude, you can ignore the longitude completely. Probably easier for me to solve this in R...
    – Spacedman
    Commented Jan 30, 2016 at 14:48


Browse other questions tagged or ask your own question.