Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PIL import Image
- BORDER_WIDTH = 5
- TARGET_COLOR = (255,0,0)
- #using both of these as globals because I'm too lazy to pass them to every function
- img = Image.open("sample.png")
- pix = img.load()
- def neighbor_coords(x,y):
- for dx,dy in ((0,1), (0,-1), (1,0), (-1,0)):
- if 0 <= x+dx < img.size[0] and 0 <= y+dy <= img.size[1]:
- yield x+dx, y+dy
- def flood_fill(x,y):
- color = pix[x,y]
- seen = set()
- to_visit = {(x,y)}
- while to_visit:
- x,y = to_visit.pop()
- #print(len(to_visit), len(seen), x,y, pix[x,y])
- seen.add((x,y))
- for nx, ny in neighbor_coords(x,y):
- if pix[nx,ny] == color and (nx,ny) not in seen:
- to_visit.add((nx,ny))
- return seen
- def get_features():
- features = []
- seen = set()
- for i in range(img.size[0]):
- for j in range(img.size[1]):
- if pix[i,j] == TARGET_COLOR and (i,j) not in seen:
- feature = flood_fill(i,j)
- seen.update(feature)
- features.append(feature)
- return features
- def is_rectangle(feature):
- left = min(p[0] for p in feature)
- right = max(p[0] for p in feature)
- top = min(p[1] for p in feature)
- bottom = max(p[1] for p in feature)
- for delta in range(BORDER_WIDTH):
- for i in range(left+delta, right+1-delta):
- if (i, top+delta) not in feature: return False
- if (i, bottom-delta) not in feature: return False
- for j in range(top+delta, bottom+1-delta):
- if (left+delta, j) not in feature: return False
- if (right-delta, j) not in feature: return False
- return True
- features = get_features()
- print("Found {} feature(s).".format(len(features)))
- rects = list(filter(is_rectangle, features))
- print("Found {} rectangle(s).".format(len(rects)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement