Created
September 3, 2011 01:04
-
-
Save adambard/1190335 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def find_largest_contiguous_region(countsarray): | |
""" | |
Find the contiguous regions in countsarray using the modified | |
flood count algorithm described in get_flood_count | |
""" | |
Q = countsarray.copy() | |
points_checked = [] | |
rows, cols = Q.shape | |
best_score = 0 | |
best_ind = -1 | |
best_point = (0, 0) | |
for i in range(rows): | |
for j in range(cols): | |
if Q[i][j] >= 0: | |
score = get_flood_count(Q, i, j, Q[i][j]) | |
if score > best_score: | |
best_score = score | |
best_ind = countsarray[i][j] | |
best_point = (i, j) | |
# Generate a nice little display | |
print countsarray | |
print "Best score: {0:d} ({1:d}, {2:d})".format(best_score, best_point[0], best_point[1]) | |
if best_score < 3: | |
raise NoPointFoundException("No point found.") | |
return best_point | |
def get_flood_count(Q, i, j, target, replacement=-1): | |
""" | |
A modified flood count algorithm. | |
Makes some assumptions about the input, namely: | |
1. Input array is small enough not to overflow the stack | |
2. Input array is numeric, and | |
3. Input array is wholly positive (or at least, has no -1's) | |
>>> Q = numpy.array([[1,1,2,4], [1, 3, 5, 7]]) | |
>>> get_flood_count(Q, 0, 0, Q[0][0]) | |
3 | |
""" | |
s = Q.shape | |
if i < 0 or j < 0 or i >= s[0] or j >= s[1] or Q[i][j] != target: | |
return 0 | |
# Q[i][j] == target_ind | |
Q[i][j] = replacement | |
return 1 + (get_flood_count(Q, i+1, j, target, replacement) + | |
get_flood_count(Q, i, j+1, target, replacement) + | |
get_flood_count(Q, i-1, j, target, replacement) + | |
get_flood_count(Q, i, j-1, target, replacement)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment