Coder Social home page Coder Social logo

Comments (5)

SharifAmit avatar SharifAmit commented on June 2, 2024

Hi,

Sorry for the late reply. I was busy with other projects.

I have uploaded the code for evaluation. (Link : https://github.com/SharifAmit/RVGAN/blob/master/eval.py)

If you find any problem with running the codes or results , please open an issue.

Thanks!

from rvgan.

htx-rest avatar htx-rest commented on June 2, 2024

image

from rvgan.

SharifAmit avatar SharifAmit commented on June 2, 2024

The printed confusion matrix should be 2-by-2. However it looks 3-by-3 in your attached image.

Did you change anything in the eval file ?

In you image it says the error is in 179 line as given below, however in the original eval.py file it is line 188.

tn, fp, fn, tp = confusion.ravel()   

Also can you print the following before the above line ?

print(np.unique(y_true))
print(np.unique(y_pred))

It should give you the same number output for both the lines.

If it doesn't I believe either your y_true or y_pred is not int or float type. So its considering 1 and 1.0 as different values.

from rvgan.

SharifAmit avatar SharifAmit commented on June 2, 2024

Please open the issue, if your problem still persists.

Thanks

from rvgan.

Medicmind avatar Medicmind commented on June 2, 2024

I had the same issue of a 3x3 confusion matrix but it because had to use jaccard_score instead of jaccard_similarity_score because of sklearn version issues and jaccard_score doesn't have a normalize parameter. So y_true has values 0 an 255 while y_pred is 0 an 1 meaning there is 3 values all up. If add the line y_true[y_true==255]=1 it normalizes y_true and gives you a 2x2 confusion matrix instead of 3x3. I have the entire eval code below:

import glob
import os
import time
import argparse
import numpy as np
from PIL import Image
from libtiff import TIFF
import tensorflow as tf
import cv2
import keras
from tensorflow.keras.optimizers import Adam
from keras.models import Model
import keras.backend as K
from src.model import coarse_generator,fine_generator
from skimage.metrics import structural_similarity as ssim
from sklearn.metrics import jaccard_score
#from sklearn.metrics import jaccard_similarity_score
from sklearn.metrics import confusion_matrix,precision_recall_curve,f1_score,roc_auc_score,auc,recall_score, auc,roc_curve


global g_local_model
global g_global_model

def normalize_pred(img,mask):
    img = np.reshape(img,[1,128,128,3])
    mask = np.reshape(mask,[1,128,128,1])
    img_coarse = tf.image.resize(img, (64,64), method=tf.image.ResizeMethod.LANCZOS3)
    img_coarse = (img_coarse - 127.5) / 127.5
    img_coarse = np.array(img_coarse)
    mask_coarse = tf.image.resize(mask, (64,64), method=tf.image.ResizeMethod.LANCZOS3)
    mask_coarse = (mask_coarse - 127.5) / 127.5
    mask_coarse = np.array(mask_coarse)
    
    _,x_global = g_global_model.predict([img_coarse,mask_coarse])
    #print('uuu',x_global.shape, np.min(x_global),np.max(x_global))  # (1, 64, 64, 128) -4.0635333 16.58276
    img = (img - 127.5) / 127.5
    mask = (mask - 127.5) / 127.5
    X_fakeB = g_local_model.predict([img,mask,x_global])
    X_fakeB = (X_fakeB + 1) /2.0
    X_fakeB = cv2.normalize(X_fakeB, None, alpha = 0, beta = 255, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
    pred_img = X_fakeB[:,:,:,0]
    return np.asarray(pred_img,dtype=np.float32)


def strided_crop(img, mask, img_h,img_w,height, width,stride=1):
  
    full_prob = np.zeros((img_h, img_w),dtype=np.float32)
    full_sum = np.ones((img_h, img_w),dtype=np.float32)
    
    max_x = int(((img.shape[0]-height)/stride)+1)
    #print("max_x:",max_x)
    max_y = int(((img.shape[1]-width)/stride)+1)
    #print("max_y:",max_y)
    max_crops = (max_x)*(max_y)
    i = 0
    for h in range(max_x):
        for w in range(max_y):
                crop_img_arr = img[h * stride:(h * stride) + height,w * stride:(w * stride) + width]
                crop_mask_arr = mask[h * stride:(h * stride) + height,w * stride:(w * stride) + width]
                pred = normalize_pred(crop_img_arr,crop_mask_arr)
                crop_img_arr 
                full_prob[h * stride:(h * stride) + height,w * stride:(w * stride) + width] += pred[0]
                full_sum[h * stride:(h * stride) + height,w * stride:(w * stride) + width] += 1
                i = i + 1
    out_img = full_prob / full_sum
    return out_img




if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('--test_data', type=str, default='DRIVE', required=True, choices=['DRIVE','CHASE','STARE'])
    parser.add_argument('--weight_name_global',type=str, help='path/to/global/weight/.h5 file', required=True)
    parser.add_argument('--weight_name_local',type=str, help='path/to/local/weight/.h5 file', required=True)
    parser.add_argument('--stride', type=int, default=3, help='For faster inference use stride 16/32, for better result use stride 3.')
    args = parser.parse_args() 

## Input dimensions

image_shape_fine = (128,128,3)
mask_shape_fine = (128,128,1)
label_shape_fine = (128,128,1)
image_shape_x_coarse = (64,64,128)
image_shape_coarse = (64,64,3)
mask_shape_coarse = (64,64,1)
label_shape_coarse = (64,64,1)
img_shape_g = (64,64,3)
ndf=64
ncf=128
nff=128

## Load models
K.clear_session()
opt = Adam()
g_local_model = fine_generator(x_coarse_shape=image_shape_x_coarse,input_shape=image_shape_fine,mask_shape=mask_shape_fine,nff=nff)
print("loc",args.weight_name_local)
g_local_model.load_weights(args.weight_name_local)
g_local_model.compile(loss='mse', optimizer=opt)
g_global_model = coarse_generator(img_shape=image_shape_coarse,mask_shape=mask_shape_coarse,ncf=ncf)
g_global_model.load_weights(args.weight_name_global)
g_global_model.compile(loss='mse',optimizer=opt)


## Find file numbers,paths or names
if args.test_data == 'DRIVE':
    limit = 20
elif args.test_data == 'CHASE':
    filenames = glob.glob("CHASE/test/images/*.jpg")
    limit = len(filenames)

elif args.test_data == 'STARE':
    arr = ["im0001","im0082","im0236","im0319"]
    limit = 4


## Iterating for each image

#960,999
w,h =584,565
y_true = np.zeros((limit,w,h),dtype=np.float32)
y_pred = np.zeros((limit,w,h),dtype=np.float32)
y_pred_auc = np.zeros((limit,w,h),dtype=np.float32)
c = 0
for i in range(0,limit):

    if args.test_data == 'DRIVE':
        
        if i<9:
            ind = str(0)
        else:
            ind = str("")
        label_name = "/home/ubuntu/efs/imagesets/drive/test/1st_manual/"+ind+str(i+1)+"_manual1.gif"
        print("file",label_name,i)
        label = Image.open(label_name)
        label_arr = np.asarray(label,dtype=np.float32)
        img_name = "/home/ubuntu/efs/imagesets/drive/test/images/"+ind+str(i+1)+"_test.tif"
        tif = TIFF.open(img_name)
        img_arr = tif.read_image(tif)
        img_arr = np.asarray(img_arr,dtype=np.float32)
        mask_name = "/home/ubuntu/efs/imagesets/drive/test/mask/"+ind+str(i+1)+"_test_mask.gif"
        mask = Image.open(mask_name)
        mask_arr = np.asarray(mask,dtype=np.float32)

    elif args.test_data == 'CHASE':
        k = filenames[i].split('/')
        k = k[-1].split('.')[0]
        label_name = "CHASE/test/labels/"+k+"_1stHO.png"
        label = Image.open(label_name)
        label_arr = np.asarray(label,dtype=np.float32)
        img_name = "CHASE/test/images/"+k+".jpg"
        img = Image.open(img_name)
        img_arr = np.asarray(img,dtype=np.float32)
        mask_name = "CHASE/test/mask/"+k+"_mask.png"
        mask = Image.open(mask_name)
        mask_arr = np.asarray(mask,dtype=np.float32)

    elif args.test_data == 'STARE':
        label_name = "STARE/test/labels-ah/"+arr[i]+".ah.ppm"
        label = Image.open(label_name)
        label_arr = np.asarray(label,dtype=np.float32)
        img_name = "STARE/test/stare-original-images/"+arr[i]+".ppm"
        img = Image.open(img_name)
        img_arr = np.asarray(img,dtype=np.float32)
        mask_name = "STARE/test/mask/"+arr[i]+"_mask.png"
        mask = Image.open(mask_name)
        mask_arr = np.asarray(mask,dtype=np.float32)


    ## Get the output predictions as array

    ## Stride =3 (best result),  Stride = 32 (faster result).
    out_img = strided_crop(img_arr, mask_arr, mask_arr.shape[0], mask_arr.shape[1], 128, 128,args.stride)

    print("cnt",np.count_nonzero(out_img),out_img.shape)
    out_img[mask_arr==0] = 0
    y_pred_auc[c,:,:] = out_img

    out_img[out_img>=0.5] = 1
    out_img[out_img<0.5] = 0
    y_true[c,:,:] = label_arr 
    y_pred[c,:,:] = out_img
    c = c +1
    
y_true[y_true==255]=1
y_true = y_true.flatten()
y_pred = y_pred.flatten()
y_pred_auc = y_pred_auc.flatten()
print("y_true",y_true.shape,np.unique(y_true),"y_pred",y_pred.shape,np.unique(y_pred))
confusion = confusion_matrix(y_true, y_pred)
print('confusion',confusion)

tn, fp, fn, tp = confusion.ravel()   
metric_cal = time.time()
if float(np.sum(confusion)) != 0:
    accuracy =  float(confusion[0, 0] + confusion[1, 1]) / float(np.sum(confusion))
print("Global Accuracy: " + str(accuracy))
specificity = 0
if float(confusion[0, 0] + confusion[0, 1]) != 0:
    specificity = tn / (tn + fp)
print("Specificity: " + str(specificity))
sensitivity = 0
if float(confusion[1, 1] + confusion[1, 0]) != 0:
    sensitivity = tp / (tp + fn) 
print("Sensitivity: " + str(sensitivity))

precision = 0
if float(confusion[1, 1] + confusion[0, 1]) != 0:
    precision = tp / (tp + fp) 
print("Precision: " + str(precision))


F1_score = 2*tp/(2*tp+fn+fp) 
print("F1 score (F-measure): " + str(F1_score))

AUC_ROC = roc_auc_score(y_true, y_pred_auc)
print("AUC_ROC: " + str(AUC_ROC))

ssim = ssim(y_true, y_pred, data_range=y_true.max()-y_true.min())
print("SSIM: " + str(ssim))

meanIOU = jaccard_score(y_true,y_pred) #,pos_label=255.0) #normalize=True)
print("meanIOU: " + str(meanIOU))


from rvgan.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.