Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # // Start Values //
- # Image Data, (1 -> Green, 0 -> Not Green)
- coordMatrix = [
- [0,0,0,0,0,0],
- [1,1,0,0,1,0],
- [0,0,0,1,1,1],
- [1,0,0,0,0,0],
- [1,1,0,1,0,0]
- ]
- # Image Dimensions
- imageWidth = 6
- imageHeight = 5
- # All found green pixels
- foundPixels = []
- # All found green regions
- numberOfRegions = 0
- # // Support Functions //
- # Check if pixel exists. If pixel exists then get pixel coordinates, else ignore
- def getPixel(x,y):
- if (
- x >= 0 and y >= 0 # if not negative
- and x < imageWidth and y < imageHeight # If Within The Image Dimensions
- ):
- return coordMatrix[y][x]
- # To Check If Program Has Already Considered This Cell
- def checkIfCounted(x,y):
- if [x,y] in foundPixels:
- return True
- return False
- def addSurroundingCells(xOr,yOr):
- for y in range(yOr-1,yOr+2): # Looping through pixels (y-1) to (y+1) ...
- for x in range(xOr-1, xOr+2): # ... and (x-1) to (x+1)
- if getPixel(x,y) == 1: # Checking If Cell Is 1 (Or Green)
- if not checkIfCounted(x,y):
- foundPixels.append([x,y]) # Adding The Current Surrounding Cell
- addSurroundingCells(x,y) # Re-Looping To Add Other Connected Cells
- # // Main Loop Through Full Image //
- # x -> row, y -> column
- for i, y in enumerate(coordMatrix): # i -> index (0,1,2...), y = value in image (pixel color)
- if 1 in y: # Only check all values inside row if 1 is found (in that row)
- for j, x in enumerate(y): # j -> index (0,1,2...), x = value in image (pixel color)
- if x == 1:
- xCoord = j
- yCoord = i
- if not checkIfCounted(xCoord, yCoord): # if already counted then ignore, else count for all connected cells
- addSurroundingCells(xCoord, yCoord) # Add all surrounding cells
- numberOfRegions += 1
- print(numberOfRegions)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement