Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def find_optimal_threshold(self, hist):
- """analyses a histogram it to find the optimal threshold value assuming a bimodal histogram
- takes as input
- hist: a bimodal histogram
- returns: an optimal threshold value"""
- threshold = 0
- threshold = -1
- thresholdValue = 1
- numPixels = sum(hist)
- weight = 1.0 / numPixels
- for j in hist[1: -1]:
- bWeight = np.sum(hist[:j]) * weight
- fWeight = np.sum(hist[j:]) * weight
- backgroundMean = np.mean(hist[:j])
- foregroundMean = np.mean(hist[j:])
- value = bWeight * fWeight * (backgroundMean-foregroundMean) ** 2
- if value > thresholdValue:
- threshold = j
- thresholdValue = value
- #print(threshold)
- return threshold
- def encode_image(self,binary_image):
- """
- Compress the image
- takes as input:
- image: binary_image
- returns run length code
- """
- rows, columns = binary_image.shape
- rle_code = []
- for row_iter in range(0, rows):
- count = 0 # This is how many pixels to replicate.
- replicate = binary_image[row_iter, 0] # This is the pixel we want to reproduce.
- for column_iter in range(0, columns):
- pixel = binary_image[row_iter, column_iter]
- if pixel == replicate:
- count += 1
- else:
- rle_code += [count]
- rle_code += [replicate]
- replicate = pixel
- count = 1
- rle_code += [count]
- rle_code += [replicate]
- print(len(rle_code))
- return rle_code
- def decode_image(self, rle_code, height , width):
- """
- Get original image from the rle_code
- takes as input:
- rle_code: the run length code to be decoded
- Height, width: height and width of the original image
- returns decoded binary image
- """
- original_image = np.zeros(shape=(height, width), dtype=np.uint8)
- code_iter = 0
- count = rle_code[0]
- replicate = rle_code[1]
- for row_iter in range(0, height):
- for column_iter in range(0, width):
- if count < 1:
- code_iter += 2
- count = rle_code[code_iter]
- replicate = rle_code[code_iter+1]
- original_image[row_iter, column_iter] = replicate
- count -= 1
- return original_image #replace zeros with image reconstructed from rle_Code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement