Advertisement
_Lunar

Number Of Regions

Aug 6th, 2022
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. # // Start Values //
  2.  
  3. # Image Data, (1 -> Green, 0 -> Not Green)
  4. coordMatrix = [
  5.   [0,0,0,0,0,0],
  6.   [1,1,0,0,1,0],
  7.   [0,0,0,1,1,1],
  8.   [1,0,0,0,0,0],
  9.   [1,1,0,1,0,0]
  10. ]
  11.  
  12. # Image Dimensions
  13. imageWidth = 6
  14. imageHeight = 5
  15.  
  16. # All found green pixels
  17. foundPixels = []
  18. # All found green regions
  19. numberOfRegions = 0
  20.  
  21. # // Support Functions //
  22.  
  23. # Check if pixel exists. If pixel exists then get pixel coordinates, else ignore
  24. def getPixel(x,y):
  25.   if (
  26.     x >= 0 and y >= 0 # if not negative
  27.     and x < imageWidth and y < imageHeight # If Within The Image Dimensions
  28.   ):
  29.     return coordMatrix[y][x]
  30.  
  31. # To Check If Program Has Already Considered This Cell
  32. def checkIfCounted(x,y):
  33.   if [x,y] in foundPixels:
  34.     return True
  35.   return False
  36.  
  37. def addSurroundingCells(xOr,yOr):
  38.  
  39.   for y in range(yOr-1,yOr+2): # Looping through pixels (y-1) to (y+1) ...
  40.     for x in range(xOr-1, xOr+2): # ... and (x-1) to (x+1)
  41.    
  42.         if getPixel(x,y) == 1: # Checking If Cell Is 1 (Or Green)
  43.           if not checkIfCounted(x,y):
  44.          
  45.             foundPixels.append([x,y]) # Adding The Current Surrounding Cell  
  46.             addSurroundingCells(x,y) # Re-Looping To Add Other Connected Cells
  47.  
  48. # // Main Loop Through Full Image //
  49.  
  50. # x -> row, y -> column
  51. for i, y in enumerate(coordMatrix): # i -> index (0,1,2...), y = value in image (pixel color)
  52.  
  53.   if 1 in y: # Only check all values inside row if 1 is found (in that row)
  54.     for j, x in enumerate(y): # j -> index (0,1,2...), x = value in image (pixel color)
  55.       if x == 1:
  56.      
  57.         xCoord = j
  58.         yCoord = i
  59.  
  60.         if not checkIfCounted(xCoord, yCoord): # if already counted then ignore, else count for all connected cells
  61.           addSurroundingCells(xCoord, yCoord) # Add all surrounding cells
  62.           numberOfRegions += 1
  63.          
  64. print(numberOfRegions)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement