Commit f2e5c6ad authored by Simon Madec's avatar Simon Madec
Browse files

first test co

parents
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 25 15:33:26 2017
@author: simadec
"""
import glob
from returnBoundBoxes import returnBound
for dataset in [4]:
pathModel = r'D:\Home\Simon_Data\ExpeManipProjet\stemCouting\python\models2\object_detection\training_{}'.format(dataset)
pathModel = r'D:\Home\Simon_Data\ExpeManipProjet\stemCouting\python\models2\object_detection\training_4'
print(pathModel)
for model in glob.glob(pathModel + r'\frozen_inference_graph_*.pb'): #todo remplacer 4000 par *
print(model)
# returnBound(model,r'D:\Home\Simon_Data\ExpeManipProjet\stemCouting\date2','Dataset-{}'.format(dataset),dataset)
returnBound(model,r'D:\Home\Simon_Data\ExpeManipProjet\stemCouting\date2','Dataset-4',dataset)
# returnBound(model,r'D:\Home\Simon_Data\ExpeManipProjet\stemCouting\date3\6-14-finished','Dataset-4',dataset)
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 17:09:33 2018
@author: simadec
"""
# -*- coding: utf-8 -*-
"""
This function return all the CSV score and bounding box along with some indices like if the boundix box is have some border with the borders of the images.
Not that this function crop the 6000x4000 images by 1000x1000 with a 50% overlap
"""
def returnBound(MODEL_NAME,pathIm,output,dataset):
# coding: utf-8
import numpy as np
import tensorflow as tf
import glob
from PIL import Image
# # Model preparation
# Path to frozen detection graph. This is the actual model that is used for the object detection.
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
print('coucou on va lire le model')
with tf.gfile.GFile(MODEL_NAME, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
## Loading label map
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
print('coucou line 31 on va ouvrir une session tensorlfow')
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
# Definite input and output Tensors for detection_graph
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
listCSV = glob.glob(output + r'/*.csv')
temp2 = MODEL_NAME.split('_')
temp2 = temp2[len(temp2)-1]
temp2 = temp2.split('.')
temp2 = temp2[0]
for image_path in glob.glob(pathIm + '/*.JPG'):
print(image_path)
temp = image_path.split('\\')
temp = temp[len(temp)-1]
temp = temp.split('.')
temp = temp[0]
numIm = temp
print(temp)
indExist = False
for i in listCSV:
#print(i)
#print(output + "\{}_box_{}.csv".format(numIm,temp))
if output + "\{}_box_{}.csv".format(numIm,temp2) == i:
indExist = True
print('on a deja calculer cette image')
if indExist == False: #si le csv n'a pas déja été calculer .
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
scoresCumul = []
boxesCumul= []
indCumul = []
if dataset==4 or (dataset==7):
# ici ca va depéndre de la dataset ...
rangeI = [500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500]
rangeJ = [500,1000,1500,2000,2500,3000,3500]
sizeImPer2 = 500
elif dataset==5 or (dataset==8):
rangeI = [750,1500,2250,3000,3750,4500,5250]
rangeJ = [750,1375,2000,2625,3250]
sizeImPer2 = 750
elif dataset==6 or (dataset==9):
rangeI = [1000,2000,3000,4000,5000]
rangeJ = [1000,2000,3000,4000]
sizeImPer2 = 1000
elif dataset==10:
rangeI = [1500,3000,4500]
rangeJ = [1500,2500]
sizeImPer2 = 1500
elif dataset==11:
rangeI = [2000,4000]
rangeJ = [2000]
sizeImPer2 = 1500
elif dataset==12:
rangeI = [250]
rangeJ = [250]
sizeImPer2 = 250
for i in rangeI: # loop de 1 à 6 pour parce que 1 à 6000 ...
for j in rangeJ:
image_np1 = image_np[j-sizeImPer2:j+sizeImPer2,i-sizeImPer2:i+sizeImPer2]
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np1, axis=0)
# Actual detection.
(boxes, scores, classes, num) = sess.run(
[detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
ind = scores>0
scores = scores[ind]
boxes = boxes[ind,0:4]
#probleme c nul
indiceO = np.zeros(len(boxes))
print('num epis dans un patch : {}'.format(len(boxes)))
for ii in range(0,len(boxes)):
if (boxes[ii,0]<0.01) or (boxes[ii,1]<0.01) or (boxes[ii,2]>0.99) or (boxes[ii,3]>0.99) :
indiceO[ii] = 1
else:
indiceO[ii] = 0
boxes[:,0] = (boxes[:,0]*sizeImPer2*2 +j-sizeImPer2)/4000 #ou moins 1000
boxes[:,1] = (boxes[:,1]*sizeImPer2*2 +i-sizeImPer2)/6000
boxes[:,2] = (boxes[:,2]*sizeImPer2*2 +j-sizeImPer2)/4000
boxes[:,3] = (boxes[:,3]*sizeImPer2*2 +i-sizeImPer2)/6000
scoresCumul = np.concatenate((scoresCumul,scores),axis=0)
indCumul = np.concatenate((indCumul,indiceO),axis=0)
if len(boxesCumul)==0:
boxesCumul = boxes
#print('length box null, carefull if step > 1000')
else:
boxesCumul = np.concatenate((boxesCumul,boxes),axis=0)
boxesCumul[:,0]=boxesCumul[:,0]*4000
boxesCumul[:,1]=boxesCumul[:,1]*6000
boxesCumul[:,2]=boxesCumul[:,2]*4000
boxesCumul[:,3]=boxesCumul[:,3]*6000
temp = MODEL_NAME.split('_')
temp = temp[len(temp)-1]
temp = temp.split('.')
temp = temp[0]
print('Step ' + temp)
np.savetxt(output + "/{}_box_{}.csv".format(numIm,temp), boxesCumul, delimiter=",")
np.savetxt(output + "/{}_Score_{}.csv".format(numIm,temp), scoresCumul, delimiter=",")
np.savetxt(output + "/{}_Indice_{}.csv".format(numIm,temp), indCumul, delimiter=",")
def returnBound_gan(MODEL_NAME, pathIm, output, dataset):
# coding: utf-8
from skimage.transform import resize
import numpy as np
import tensorflow as tf
import glob
from PIL import Image
import keras
from keras.models import load_model
from keras_contrib.layers.normalization import InstanceNormalization
model_BA = load_model(r'D:\Home\Simon_Data\ExpeManipProjet\GAN\Keras-GAN-master\cyclegan\saved_model\g_BA.h5', custom_objects={'InstanceNormalization': InstanceNormalization})
# # Model preparation
# Path to frozen detection graph. This is the actual model that is used for the object detection.
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
print('coucou on va lire le model')
with tf.gfile.GFile(MODEL_NAME, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
## Loading label map
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
print('coucou line 31 on va ouvrir une session tensorlfow')
# Definite input and output Tensors for detection_graph
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
listCSV = glob.glob(output + r'/*.csv')
temp2 = MODEL_NAME.split('_')
temp2 = temp2[len(temp2) - 1]
temp2 = temp2.split('.')
temp2 = temp2[0]
for image_path in glob.glob(pathIm + '/*.JPG'):
print(image_path)
temp = image_path.split('\\')
temp = temp[len(temp) - 1]
temp = temp.split('.')
temp = temp[0]
numIm = temp
print(temp)
indExist = False
for i in listCSV:
# print(i)
# print(output + "\{}_box_{}.csv".format(numIm,temp))
if output + "\{}_box_{}.csv".format(numIm, temp2) == i:
indExist = True
print('on a deja calculer cette image')
if indExist == False: # si le csv n'a pas déja été calculer .
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
scoresCumul = []
boxesCumul = []
indCumul = []
if dataset == 4:
# ici ca va depéndre de la dataset ...
rangeI = [256,512,768,1024,1280,1536,1792,2048,2304,2560,2816,3072,3328,3584,3840,4096,4352,4608,4864,5120,5376,5632,5744]
rangeJ = [256,512,768,1024,1280,1536,1792,2048,2304,2560,2816,3072,3328,3584,3744]
sizeImPer2 = 256
for i in rangeI: # loop de 1 à 6 pour parce que 1 à 6000 ...
for j in rangeJ:
image_np1 = image_np[j - sizeImPer2:j + sizeImPer2, i - sizeImPer2:i + sizeImPer2]
X_test = np.zeros((1, 512, 512, 3), dtype=np.uint8) # pas obliger de définir ici
X_test[0] = image_np1
tsst = model_BA.predict(X_test)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
img_new = resize(tsst[0], (1000, 1000), mode='constant')
img_new_uint= np.uint8(img_new*255)
image_np_expanded = np.expand_dims((np.array(img_new_uint)), axis=0)
coucou=1
# Actual detection.
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
(boxes, scores, classes, num) = sess.run(
[detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
ind = scores > 0
scores = scores[ind]
boxes = boxes[ind, 0:4]
# probleme c nul
indiceO = np.zeros(len(boxes))
print('num epis dans un patch : {}'.format(len(boxes)))
for ii in range(0, len(boxes)):
if (boxes[ii, 0] < 0.01) or (boxes[ii, 1] < 0.01) or (boxes[ii, 2] > 0.99) or (
boxes[ii, 3] > 0.99):
indiceO[ii] = 1
else:
indiceO[ii] = 0
boxes[:, 0] = (boxes[:, 0] * sizeImPer2 * 2 + j - sizeImPer2) / 4000 # ou moins 1000
boxes[:, 1] = (boxes[:, 1] * sizeImPer2 * 2 + i - sizeImPer2) / 6000
boxes[:, 2] = (boxes[:, 2] * sizeImPer2 * 2 + j - sizeImPer2) / 4000
boxes[:, 3] = (boxes[:, 3] * sizeImPer2 * 2 + i - sizeImPer2) / 6000
scoresCumul = np.concatenate((scoresCumul, scores), axis=0)
indCumul = np.concatenate((indCumul, indiceO), axis=0)
if len(boxesCumul) == 0:
boxesCumul = boxes
# print('length box null, carefull if step > 1000')
else:
boxesCumul = np.concatenate((boxesCumul, boxes), axis=0)
boxesCumul[:, 0] = boxesCumul[:, 0] * 4000
boxesCumul[:, 1] = boxesCumul[:, 1] * 6000
boxesCumul[:, 2] = boxesCumul[:, 2] * 4000
boxesCumul[:, 3] = boxesCumul[:, 3] * 6000
temp = MODEL_NAME.split('_')
temp = temp[len(temp) - 1]
temp = temp.split('.')
temp = temp[0]
print('Step ' + temp)
np.savetxt(output + "/{}_box_{}.csv".format(numIm, temp), boxesCumul, delimiter=",")
np.savetxt(output + "/{}_Score_{}.csv".format(numIm, temp), scoresCumul, delimiter=",")
np.savetxt(output + "/{}_Indice_{}.csv".format(numIm, temp), indCumul, delimiter=",")
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment