简体   繁体   中英

How to append coordinates of all white pixels into array? OpenCV Python

how can I append the coordinates of the white pixels in the picture into arrays? I want the two white lines to be seperated into two different arrays, and then calculate max and min distance between two lines. Im quite new to OpenCV and Python, so any help or code example is greatly appriciated.

在此处输入图片说明

What's done in the below code is that we use recursion to get all the adjacent whites thus covering a whole 'line'. The recursion is easy, we just need to get the adjacent cells, maintain a check array and the work is done.

Next we need to get them in 2 separate arrays. For that we iterate through the image and pass the first array to the recursive function if it's length is 0 ie nothing has been added to it otherwise the 2nd array is passed.

The code has not been tested I'm sorry. Also this involves concepts such as recursion and is a bit tricky as well. Please notify me in comments if there are any errors or you couldn't understand any part. I'll get back to you at the earliest. Thanks

Your result coordinates are stored in arr1 and arr2.

## let image_arr be your 2d image array

check_arr = numpy.zeros(shape=(rows,cols))
arr1 = []
arr2 = []

def get_neighbour_whites(x,y,arr):
    def get_adjacent_cells( self, x_coord, y_coord ):
       result = set()
        for k,l in [(x_coord+i,y_coord+j) for i in (-1,0,1) for j in (-1,0,1) if i != 0 or j != 0]:
           if k>=0 and k<rows and l>=0 and l<cols:
                result.add((k,l))
         return result

    check_arr[x,y] = 1
    arr.append((x,y))
    adj_cells = get_adjacent_cells(x,y)

    for i,j in adj_cells:
        if image_arr[i,j]==255 and not check_arr[i,j]:
            get_neighbour_whites(i,j,arr)

for x in xrange(rows):
    for y in xrange(cols):
        if image_arr[x,y] == 255 and not check_arr[x,y]:
            get_neighbour_whites(x,y,arr1 if len(arr1)==0 else arr2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM