Skip to content
Snippets Groups Projects
Commit 3b36a6ea authored by JISHNU P's avatar JISHNU P
Browse files

Upload New File

parent 21af5b6e
No related branches found
No related tags found
No related merge requests found
%% Cell type:code id: tags:
``` python
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import cv2
from PIL import Image
```
%% Cell type:code id: tags:
``` python
A = ['020_HC.png','018_HC.png']
# x = 0
# for i in A:
# pic = cv2.imread(i,cv2.IMREAD_GRAYSCALE)
# cv2.imwrite("% 2d.png"%(x), pic)
# x += 1
```
%% Cell type:code id: tags:
``` python
pic = cv2.imread('000_HC.png',cv2.IMREAD_GRAYSCALE)
pic.shape
```
%% Output
(540, 800)
%% Cell type:code id: tags:
``` python
# print('% 2d.png'%(1))
```
%% Output
1.png
%% Cell type:code id: tags:
``` python
##################################################################################
```
%% Cell type:code id: tags:
``` python
from PIL import Image
import numpy as np
import pandas as pd
import os, os.path
from scipy import misc
import glob
import sys
from matplotlib.pyplot import imshow
import imageio
import scipy.stats
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy import optimize
import random
import warnings
warnings.filterwarnings('ignore')
import cv2
```
%% Cell type:code id: tags:
``` python
path = "200.png"
arr = misc.imread(path, flatten=True)
print ("initial image")
imshow(arr, cmap='gray');
```
%% Output
initial image
%% Cell type:code id: tags:
``` python
tmp = plt.gcf().clear()
```
%% Output
%% Cell type:code id: tags:
``` python
initial_probability = {"2.png": 0.75, "MRI1.jpg" : 0.25}
number_of_pixels = arr.size
class_info = []
paths= ["2.png", "MRI1.jpg" ]
for path in paths:
tmp_arr = misc.imread(path, flatten=True)
class_mean = np.mean(tmp_arr)
class_var = np.var(tmp_arr)
class_freq = len(tmp_arr)
class_probabilty = class_freq/number_of_pixels
class_info.append([initial_probability[path], class_mean, class_var])
print ("class_info")
print (class_info)
```
%% Cell type:code id: tags:
``` python
def pdf_of_normal(x, mean, var):
return (1/np.sqrt(2 * np.pi * var))*np.exp(-((x-mean)**2)/(2*var))
```
%% Cell type:code id: tags:
``` python
arr.shape
```
%% Output
(540, 800)
%% Cell type:code id: tags:
``` python
def naive_bayes_predict (arr, class_info, fixed_pixels_index=[], correct_arr = []):
predict_array = np.zeros((len(arr), len(arr[0])), dtype=float)
class_color = [50,200]
for i in range(0, len(arr)):
for j in range(0, len(arr[0])):
if (len(fixed_pixels_index)>0 and len(correct_arr)>0 and fixed_pixels_index[i][j]==1):
predict_array[i][j]=correct_arr[i][j]
continue
max_probabilty = 0
best_class = -1
val = arr[i][j]
for cls_index in range(len(class_info)):
cls_p = class_info[cls_index][0]
mean = class_info[cls_index][1]
var = class_info[cls_index][2]
pos =pdf_of_normal(val, mean, var)
cls_posterior = cls_p * pos
if (cls_posterior > max_probabilty):
max_probabilty = cls_posterior
best_class = cls_index
predict_array[i][j] = class_color[best_class]
return predict_array
```
%% Cell type:code id: tags:
``` python
def distance (x,y):
a = x-y
a = a*a
return np.sqrt(np.sum(a))
```
%% Cell type:code id: tags:
``` python
def differnce(a,b):
if (a==b):
return -1
else:
return 1
```
%% Cell type:code id: tags:
``` python
def initial_energy_function(initial_w, pixels, betha, cls_info, neighbors_indices):
w = initial_w
energy = 0.0
rows = len(w)
cols = len(w[0])
for i in range(0, len(w)):
for j in range(0, len(w[0])):
mean = cls_info[int (w[i][j])][1]
var = cls_info[int (w[i][j])][2]
energy += np.log(np.sqrt(2*np.pi*var))
energy += ((pixels[i][j]-mean)**2)/(2*var)
for a,b in neighbors_indices:
a +=i
b +=j
if 0<=a<rows and 0<=b<cols:
energy += betha * differnce(w[i][j], w[a][b])
return energy
```
%% Cell type:code id: tags:
``` python
def exponential_schedule(step_number, current_t, initial_temp, constant=0.99):
return current_t*constant
def logarithmical_multiplicative_cooling_schedule(step_number, current_t, initial_temp, constant=1.0):
return initial_temp / (1 + constant * np.log(1+step_number))
def linear_multiplicative_cooling_schedule(step_number, current_t, initial_temp, constant=1.0):
return initial_temp / (1 + constant * step_number)
```
%% Cell type:code id: tags:
``` python
def delta_enegry(w, index, betha, new_value, neighbors_indices, pixels, cls_info):
initial_energy = 0
(i,j) = index
rows = len(w)
cols = len(w[0])
mean = cls_info[int(w[i][j])][1]
var = cls_info[int(w[i][j])][2]
initial_energy += np.log(np.sqrt(2*np.pi*var))
initial_energy += ((pixels[i][j]-mean)**2)/(2*var)
for a,b in neighbors_indices:
a +=i
b +=j
if 0<=a<rows and 0<=b<cols:
initial_energy += betha * differnce(w[i][j], w[a][b])
new_energy = 0
mean = cls_info[new_value][1]
var = cls_info[new_value][2]
new_energy += np.log(np.sqrt(2*np.pi*var))
new_energy += ((pixels[i][j]-mean)**2)/(2*var)
# print("/////// \n first enegry", new_energy)
for a,b in neighbors_indices:
a +=i
b +=j
if 0<=a<rows and 0<=b<cols:
new_energy += betha * differnce(new_value, w[a][b])
# print ("END energy", new_energy)
return new_energy - initial_energy
```
%% Cell type:code id: tags:
``` python
def simulated_annealing(init_w, class_labels, temprature_function,
pixels, betha, cls_info, neighbors_indices, max_iteration=10000,
initial_temp = 1000, known_index=[], correct_arr = [], temprature_function_constant=None ):
partial_prediction=False
if (len(known_index)>0 and len(correct_arr)>0):
partial_prediction=True
w = np.array(init_w)
changed_array = np.zeros((len(w), len(w[0])))
iteration =0
x = len(w)
y = len(w[0])
current_energy = initial_energy_function(w, pixels, betha, cls_info, neighbors_indices)
current_tmp = initial_temp
while (iteration<max_iteration):
if (partial_prediction):
is_found=False
while (is_found==False):
i = random.randint(0, x-1)
j = random.randint(0, y-1)
if (known_index[i][j]==0):
is_found=True
else:
i = random.randint(0, x-1)
j = random.randint(0, y-1)
l = list(class_labels)
l.remove(w[i][j])
r = random.randint(0, len(l)-1)
new_value = l[r]
delta = delta_enegry(w, (i,j), betha, new_value, neighbors_indices, pixels, cls_info)
r = random.uniform(0, 1)
if (delta<=0):
w[i][j]=new_value
current_energy+=delta
changed_array[i][j]+=1
# print ("CHANGED better")
else:
try:
if (-delta / current_tmp < -600):
k=0
else:
k = np.exp(-delta / current_tmp)
except:
k=0
if r < k:
# print("CHANGED worse")
w[i][j] = new_value
current_energy += delta
changed_array[i][j] += 1
if (temprature_function_constant!=None):
current_tmp = temprature_function(iteration, current_tmp, initial_temp, constant =temprature_function_constant)
else:
current_tmp = temprature_function(iteration, current_tmp, initial_temp)
iteration+=1
return w, changed_array
```
%% Cell type:code id: tags:
``` python
def convert_to_class_labels(arr, inverse_array={50:0, 200:1}):
for i in range(0, len(arr)):
for j in range(0, len(arr[0])):
arr[i][j] = inverse_array[int(arr[i][j])]
```
%% Cell type:code id: tags:
``` python
def get_accuracy(arr, labels):
correct = 0
for i in range(0, len(arr)):
for j in range(0, len(arr[0])):
if (labels[i][j]==int(arr[i][j]/127)):
correct+=1
return correct/(len(arr[0])*len(arr))
```
%% Cell type:code id: tags:
``` python
plt.figure(figsize=(16, 18), dpi=80, facecolor='w', edgecolor='k')
```
%% Output
<Figure size 1280x1440 with 0 Axes>
%% Cell type:code id: tags:
``` python
u = 10
# plt.close('all')
def a_complete_set_for_part_2 (arr, class_info, max_iter=1000000,var = 10000,
betha = 100,
neighbor_indices = [[0,1],[0,-1],[1,0],[-1,0]],
class_labels = [0,1],
class_color = [50,200],
schedule= exponential_schedule,
temprature_function_constant=None):
fig, (ax1, ax2, ax3, ax4) = plt.subplots(1,4)
# fig.suptitle('Comparision', fontsize=20)
ax1.set_title("initial image")
ax1.imshow(arr, cmap='gray')
rows = len(arr)
cols = len(arr[0])
# cls_info = naive_bayes_learning(arr, noisy_arr, labels)
cls_info = class_info
initial_arr = naive_bayes_predict(arr, cls_info)
ax2.set_title('Naive Bayes image')
ax2.imshow(initial_arr, cmap='gray')
convert_to_class_labels(initial_arr)
w, test_array = simulated_annealing(initial_arr, class_labels, schedule,
arr, betha, cls_info, neighbor_indices, max_iteration=max_iter)
for i in range (0, len(w)):
for j in range(0, len(w[0])):
w[i][j] = class_color[int (w[i][j])]
ax3.set_title('CRF image')
ax3.imshow(w, cmap='gray')
cv2.imwrite('C:/Users/Ankit/Desktop/% 2d.png'%(u),w)
second_image = w
# print(first_image)
plt.rcParams["figure.figsize"] = (20,3)
ax4.set_title('differ image')
ax4.imshow(test_array, cmap='gray')
plt.show()
plt.figure(figsize=(16, 18), dpi=80, facecolor='w', edgecolor='k')
for i in A:
path = i
arr = misc.imread(path, flatten=True)
print ("initial image")
imshow(arr, cmap='gray');
initial_probability = {"2.png": 0.75, "MRI1.jpg" : 0.25}
number_of_pixels = arr.size
class_info = []
paths= ["2.png", "MRI1.jpg" ]
for path in paths:
tmp_arr = misc.imread(path, flatten=True)
class_mean = np.mean(tmp_arr)
class_var = np.var(tmp_arr)
class_freq = len(tmp_arr)
class_probabilty = class_freq/number_of_pixels
class_info.append([initial_probability[path], class_mean, class_var])
print ("class_info")
print (class_info)
a_complete_set_for_part_2(arr,class_info, max_iter=1e5, betha=1e6)
u += 1
```
%% Cell type:code id: tags:
``` python
a_complete_set_for_part_2(arr,class_info, max_iter=1e7, betha=1e6)
```
%% Output
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment