Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- from random import randint
- input = cv2.imread('input.jpg',cv2.IMREAD_GRAYSCALE)
- h,w = input.shape
- img = np.zeros((h,w), np.uint8)
- H = np.zeros((256),np.int64)
- nr = 0
- for i in range(h):
- for j in range(w):
- H[input[i,j]]+=1
- nr += 1
- nl = 0
- ul = 0.0
- ur = 0.0
- I = -1
- M = -1
- for i in range(256):
- ur += i*H[i]
- ur /= nr
- #print(ur)
- for i in range(256):
- ul = ul*nl+H[i]*i
- nl += H[i]
- ul /= nl
- ur = ur*nr-H[i]*i
- #print(i,ur)
- nr -= H[i]
- ur /= nr
- if((ul-ur)*(ul-ur)*nl*nr>M):
- M = (ul-ur)*(ul-ur)*nl*nr
- I = i
- #print(H[254]*254)
- # print(i,ul,ur,nl,nr)
- #print(I)
- for i in range(h):
- for j in range(w):
- if(input[i,j] > I):
- img[i,j] = 255
- else:
- img[i,j] = 0
- cv2.imshow('TEST', img)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
- tmp = np.zeros((h,w), np.uint64)
- ct = 1
- cp = np.zeros((53218), np.uint64)
- top = 0
- print(h,w)
- F = np.zeros((50000), np.uint64)
- def f(x):
- if(F[x]==x):
- return x
- else:
- F[x] = f(F[x])
- return F[x]
- def u(x,y):
- A = f(x)
- B = f(y)
- if(A != B):
- F[A] = B
- for i in range(50000):
- F[i] = i
- for i in range(h):
- for j in range(w):
- if(img[i,j]==255):
- if(i-1>=0 and tmp[i-1,j]!=0):
- tmp[i,j] = tmp[i-1,j]
- if(j-1>=0 and tmp[i,j-1]!=0 and tmp[i-1,j]!=tmp[i,j-1]):
- u(tmp[i,j-1],tmp[i-1,j])
- elif(j-1>=0 and tmp[i,j-1]!=0):
- tmp[i,j] = tmp[i,j-1]
- else:
- tmp[i,j] = ct
- ct += 1
- num = np.zeros((5000000), np.uint64)
- col = np.zeros((3,5000),np.uint64)
- top = ct
- ct = 1
- for i in range(top):
- if(F[i]==i):
- num[i] = ct
- col[0,ct] = randint(0,256)
- col[1,ct] = randint(0,256)
- col[2,ct] = randint(0,256)
- ct += 1
- print(top,ct)
- output = np.zeros((h,w,3), np.uint8)
- for i in range(h):
- for j in range(w):
- tmp[i,j] = num[f(tmp[i][j])]
- for i in range(h):
- for j in range(w):
- if(img[i,j]==255):
- output[i,j,0] = col[0,tmp[i,j]]
- output[i,j,1] = col[1,tmp[i,j]]
- output[i,j,2] = col[2,tmp[i,j]]
- else:
- output[i,j,0] = 0
- output[i,j,1] = 0
- output[i,j,2] = 0
- cv2.imshow('TEST', output)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement