Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. def find_optimal_threshold(self, hist):
  2. """analyses a histogram it to find the optimal threshold value assuming a bimodal histogram
  3. takes as input
  4. hist: a bimodal histogram
  5. returns: an optimal threshold value"""
  6.  
  7. threshold = 0
  8.  
  9. threshold = -1
  10. thresholdValue = 1
  11. numPixels = sum(hist)
  12. weight = 1.0 / numPixels
  13.  
  14. for j in hist[1: -1]:
  15. bWeight = np.sum(hist[:j]) * weight
  16. fWeight = np.sum(hist[j:]) * weight
  17. backgroundMean = np.mean(hist[:j])
  18. foregroundMean = np.mean(hist[j:])
  19. value = bWeight * fWeight * (backgroundMean-foregroundMean) ** 2
  20.  
  21. if value > thresholdValue:
  22. threshold = j
  23. thresholdValue = value
  24.  
  25.  
  26.  
  27. #print(threshold)
  28. return threshold
  29.  
  30. def encode_image(self,binary_image):
  31. """
  32. Compress the image
  33. takes as input:
  34. image: binary_image
  35. returns run length code
  36. """
  37.  
  38.  
  39. rows, columns = binary_image.shape
  40.  
  41. rle_code = []
  42. for row_iter in range(0, rows):
  43. count = 0 # This is how many pixels to replicate.
  44. replicate = binary_image[row_iter, 0] # This is the pixel we want to reproduce.
  45. for column_iter in range(0, columns):
  46. pixel = binary_image[row_iter, column_iter]
  47. if pixel == replicate:
  48. count += 1
  49. else:
  50. rle_code += [count]
  51. rle_code += [replicate]
  52. replicate = pixel
  53. count = 1
  54. rle_code += [count]
  55. rle_code += [replicate]
  56. print(len(rle_code))
  57. return rle_code
  58.  
  59.  
  60.  
  61. def decode_image(self, rle_code, height , width):
  62. """
  63. Get original image from the rle_code
  64. takes as input:
  65. rle_code: the run length code to be decoded
  66. Height, width: height and width of the original image
  67. returns decoded binary image
  68. """
  69.  
  70. original_image = np.zeros(shape=(height, width), dtype=np.uint8)
  71. code_iter = 0
  72. count = rle_code[0]
  73. replicate = rle_code[1]
  74.  
  75. for row_iter in range(0, height):
  76. for column_iter in range(0, width):
  77. if count < 1:
  78. code_iter += 2
  79. count = rle_code[code_iter]
  80. replicate = rle_code[code_iter+1]
  81. original_image[row_iter, column_iter] = replicate
  82. count -= 1
  83.  
  84.  
  85. return original_image #replace zeros with image reconstructed from rle_Code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement