def test_recognition_model_squeezenet(): try: keras.backend.clear_session() except: None predictor = ImagePrediction() predictor.setModelTypeAsSqueezeNet() predictor.setModelPath( os.path.join(main_folder, "data-models", "squeezenet_weights_tf_dim_ordering_tf_kernels.h5")) predictor.loadModel() images_to_image_array() result_array = predictor.predictMultipleImages( sent_images_array=all_images_array) assert isinstance(result_array, list) for result in result_array: assert "predictions" in result assert "percentage_probabilities" in result assert isinstance(result["predictions"], list) assert isinstance(result["percentage_probabilities"], list) assert isinstance(result["predictions"][0], str) assert isinstance(result["percentage_probabilities"][0], float)
def run(self): print("预测线程启动") global PredictionResult global PredictionModelPath global PredictionResult global PredictionSpeed prediction = ImagePrediction() PredictionResult.set('') if PredictionModel.get() == 'SqueezeNet': print('预测模型选中:SqueezeNet') prediction.setModelTypeAsSqueezeNet() elif PredictionModel.get() == 'ResNet50': print('预测模型选中:ResNet50') prediction.setModelTypeAsResNet() elif PredictionModel.get() == 'InceptionV3': print('预测模型选中:InceptionV3') prediction.setModelTypeAsInceptionV3() elif PredictionModel.get() == 'DenseNet121': print('预测模型选中:DenseNet121') prediction.setModelTypeAsDenseNet() PredictionModelPath = prediction_model() print('模型路径:' + PredictionModelPath) prediction.setModelPath(PredictionModelPath) speedindex = SpeedSelector.get() print('识别速度' + PredictionSpeed[speedindex - 1]) bk.clear_session() prediction.loadModel(prediction_speed=PredictionSpeed[speedindex - 1]) predictions, probabilities = prediction.predictImage( imagePath, result_count=CountSelector.get()) for eachPrediction, eachProbability in zip(predictions, probabilities): PredictionResult.set(PredictionResult.get() + "\n" + str(eachPrediction) + zh_cn(str(eachPrediction)) + " : " + str(eachProbability)) print("预测线程结束")
def classify_img(self, img): # input: Image object to classify # output: classification results in dictionary # where key is object as a string # and value is confidence level scaled 0-100 if not isinstance(img, Image.Image): return None prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() prediction.setModelPath( 'src/squeezenet_weights_tf_dim_ordering_tf_kernels.h5') prediction.loadModel() predictions, probabilities = [ elem[::-1] for elem in prediction.predictImage(img, input_type='array') ] results = {} for idx, prediction in enumerate(predictions): related_words = self.get_related_words(prediction) results.update( {word: probabilities[idx] for word in related_words}) return results
def detect_img(): # return nothing if no file if 'file' not in request.files: return jsonify("") file = request.files['file'] if file.filename == '': flash('No selected file') return jsonify("") if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(execution_path, filename)) logging.debug(os.path.join(execution_path , filename)); prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() prediction.setModelPath(os.path.join(execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5")) prediction.loadModel() predictions, probabilities = prediction.predictImage(os.path.join(execution_path, filename), result_count=5 ) results = []; for eachPrediction, eachProbability in zip(predictions, probabilities): results.append((eachPrediction, eachProbability)) os.remove(os.path.join(execution_path, filename)) return jsonify(results)
def load_models(): # load models keras.backend.clear_session() # SqueezeNet for image recognition # higher speed and intermediate accuracy predictor_sqz = ImagePrediction() predictor_sqz.setModelTypeAsSqueezeNet() predictor_sqz.setModelPath( os.path.join( MEDIA_ROOT, 'models/squeezenet_weights_tf_dim_ordering_tf_kernels.h5')) predictor_sqz.loadModel() # ResNet for image recognition # high speed and high accuracy predictor_res = ImagePrediction() predictor_res.setModelTypeAsResNet() predictor_res.setModelPath( os.path.join(MEDIA_ROOT, 'models/resnet50_weights_tf_dim_ordering_tf_kernels.h5')) predictor_res.loadModel() # RetinaNet for object detection detector_res = ObjectDetection() detector_res.setModelTypeAsRetinaNet() detector_res.setModelPath( os.path.join(MEDIA_ROOT, 'models/resnet50_coco_best_v2.0.1.h5')) detector_res.loadModel() return predictor_sqz, predictor_res, detector_res
def test_recognition_model_squeezenet(): predictor = ImagePrediction() predictor.setModelTypeAsSqueezeNet() predictor.setModelPath( os.path.join(main_folder, "data-models", "squeezenet_weights_tf_dim_ordering_tf_kernels.h5")) predictor.loadModel() predictions, probabilities = predictor.predictImage( image_input=os.path.join(main_folder, main_folder, "data-images", "1.jpg")) assert isinstance(predictions, list) assert isinstance(probabilities, list) assert isinstance(predictions[0], str) assert isinstance(probabilities[0], float)
def recognize_images(images_list, pictures_to_recognize_path, object_recognition_library_path, logged_user): for image in images_list: image_url = os.path.join(pictures_to_recognize_path, str(image)) prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() path = os.path.join(object_recognition_library_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5") prediction.setModelPath(path) prediction.setModelPath(path) prediction.loadModel() predictions, probabilities = prediction.predictImage(image_url, result_count=5) recognized_object_list = [] for eachPrediction, eachProbability in zip(predictions, probabilities): print(eachPrediction) if eachProbability > 30: recognized_object_list.append(eachPrediction) print(eachPrediction, " : ", eachProbability) print(recognized_object_list) create_unsaved_learnwords(recognized_object_list, image_url, logged_user.id)
def validateImage(predictionImage, goalImage): # load image here, not best practice but does load fast enough (less than a few seconds) prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() prediction.setModelPath( "selfcaptcha/static/algorithms/squeezenet_weights_tf_dim_ordering_tf_kernels.h5" ) prediction.loadModel() # converts goal image name to lowercase with underscores to match algo goalImage = goalImage.lower().replace(' ', '_') # tries top 5 predictions to see if they match (also must meet minimum probability requirement) bestGuesses, probabilities = prediction.predictImage(predictionImage, result_count=5) foundMatch = False foundMatchProbability = 0 for bestGuess, probability in zip(bestGuesses, probabilities): if bestGuess == goalImage and probability > 1: # must meet min probability of 1% to consider foundMatch = True foundMatchProbability = probability return (foundMatch, foundMatchProbability ) # we use probability to determine if images are duplicates
import uuid, json import os, base64, random from imageai.Prediction import ImagePrediction execution_path = os.getcwd() prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() prediction.setModelPath(os.path.join(execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5")) prediction.loadModel() def return_msg(error, msg): return_data = { "uuid": str(uuid.uuid1()), "error": error, "message": msg } print(return_data) return return_data def main_handler(event, context): imgData = base64.b64decode(json.loads(event["body"])['pic']) fileName = '/tmp/' + "".join(random.sample('zyxwvutsrqponmlkjihgfedcba', 5)) with open(fileName, 'wb') as f: f.write(imgData) resultData = {} predictions, probabilities = prediction.predictImage(fileName, result_count=5) for eachPrediction, eachProbability in zip(predictions, probabilities): resultData[eachPrediction] = eachProbability
from imageai.Prediction import ImagePrediction import os execution_path = os.getcwd() #gets current working directory inputimage = input("enter name of image you want to predict :") count = input("enter the number of predictions you want :") prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() #you can use different models prediction.setModelPath( os.path.join(execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5") ) #instead of this input the filename of your model prediction.loadModel() predictions, probabilities = prediction.predictImage(os.path.join( execution_path, inputimage), count=5) for eachPrediction, eachProbability in zip(predictions, probabilities): print(eachPrediction, " : ", eachProbability)
# Set output file path output_path = output_images_path + 'result_' + str(count) + '.jpg' # Detect print('Detecting...', output_path) detector.detectCustomObjectsFromImage(input_image=f, output_image_path=output_path, custom_objects=custom_objects, minimum_percentage_probability=40) count += 1 """ from imageai.Prediction import ImagePrediction import os model_path = '/Users/user/Desktop/segmentation/object_detection/h5/squeezenet_weights_tf_dim_ordering_tf_kernels.h5' multiple_prediction = ImagePrediction() multiple_prediction.setModelTypeAsSqueezeNet() multiple_prediction.setModelPath(model_path) multiple_prediction.loadModel() all_images_array = [] all_files = os.listdir('original/') for each_file in all_files: if (each_file.endswith(".jpg") or each_file.endswith(".png")): # /Users/user/Desktop/segmentation/object_detection/original all_images_array.append( '/Users/user/Desktop/segmentation/object_detection/original/' + each_file) print(all_images_array)
# Use Google Colab import os from imageai.Prediction import ImagePrediction !pip3 install - U tensorflow keras opencv-python !pip3 install imageai - -upgrade execution_path = os.getcwd() prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() # fast, but moderate accurate prediction.setModelPath(os.path.join( execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5")) prediction.loadModel() predictions, probabilities = prediction.predictImage( os.path.join(execution_path, "house.jpg"), result_count=5) for eachPrediction, eachProbability in zip(predictions, probabilities): print(eachPrediction, " : ", eachProbability)
from imageai.Prediction import ImagePrediction import os #This script uses Prediction classes to determine the image. execution_path = os.getcwd() prediction = ImagePrediction() prediction.setModelTypeAsSqueezeNet() #Type of the model to use prediction.setModelPath( os.path.join(execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5") ) #Path to the model. prediction.loadModel() predictions, probabilities = prediction.predictImage(os.path.join( execution_path, "maison.jpg"), result_count=5) for eachPrediction, eachProbability in zip(predictions, probabilities): print(eachPrediction, " : ", eachProbability)