문제

I have data in the following format, a list of 2d x,y coordinates:

[(6, 7), (2, 4), (8, 9), (3, 7), (5, 4), (9, 9)]

and I'm trying to iterate through the list to find the minimum bounding box in the format [(minx,miny),(maxx,miny),(maxx,maxy),(minx,maxy)]

Thus I've written the below code, however it doesn't appear to be working. Potentially to do with the fact that I'm not passing it an array rather a list. the input and code is below, print coords returns the list previously mentioned:

os.chdir("filepath")
with open ('file.csv') as csvfile:
    coords = [(int(x), int(y)) for x, y in csv.reader(csvfile, delimiter= ',')]
print coords


def bounding_box(coords):
    min_x, min_y = numpy.min(coords[0], axis=0)
    max_x, max_y = numpy.max(coords[0], axis=0)
    return numpy.array(
        [(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)])

Could anyone point me in the right direction? feel free to disregard the entire code above if its not helping.

도움이 되었습니까?

해결책

Why don't you just iterate through the list with four counters: min_x, min_y, max_x, and max_y

def bounding_box(coords):

  min_x = 100000 # start with something much higher than expected min
  min_y = 100000
  max_x = -100000 # start with something much lower than expected max
  max_y = -100000

  for item in coords:
    if item[0] < min_x:
      min_x = item[0]

    if item[0] > max_x:
      max_x = item[0]

    if item[1] < min_y:
      min_y = item[1]

    if item[1] > max_y:
      max_y = item[1]

  return [(min_x,min_y),(max_x,min_y),(max_x,max_y),(min_x,max_y)]

Using your example input:

bounding_box([(6, 7), (2, 4), (8, 9), (3, 7), (5, 4), (9, 9)])
>> [(2, 4), (9, 4), (9, 9), (2, 9)]

다른 팁

The issue you're having is that you are searching for a vector min/max and instead you should be searching by each of the verctor dimensions (two in your case). so you should look for the min for X and the min for Y and the same for the max.

The correct approach would be:

min_x, min_y = numpy.min(coords[...,0]), numpy.min(coords[...,1])
max_x, max_y = numpy.max(coords[...,0]), numpy.max(coords[...,1])
return numpy.array(
    [(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)])

coords[...,0] and coords[...,1] means that you are selecting values from a specific dimension (X or Y respectively).

In order for all of this to work properly you should also make the list of coordinates to be a numpy twodimensional array instead of list of tuples.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top