Beispiel #1
0
def recognize(image_path: str,
              weights_path: str,
              config: GlobalConfig,
              is_vis=True):
    logger = LogFactory.get_logger()
    image = load_and_resize_image(image_path)

    inputdata = tf.placeholder(dtype=tf.float32,
                               shape=[1, 32, 100, 3],
                               name='input')

    net = CRNN(phase='Test', hidden_nums=256, seq_length=25, num_classes=37)

    with tf.variable_scope('shadow'):
        net_out = net.build(inputdata=inputdata)

    decodes, _ = tf.nn.ctc_beam_search_decoder(inputs=net_out,
                                               sequence_length=25 * np.ones(1),
                                               merge_repeated=False)

    decoder = TextFeatureIO()

    # config tf session
    sess_config = tf.ConfigProto()
    sess_config.gpu_options.per_process_gpu_memory_fraction = config.get_gpu_config(
    ).memory_fraction
    sess_config.gpu_options.allow_growth = config.get_gpu_config(
    ).is_tf_growth_allowed()

    # config tf saver
    saver = tf.train.Saver()

    sess = tf.Session(config=sess_config)

    with sess.as_default():
        saver.restore(sess=sess, save_path=weights_path)
        preds = sess.run(decodes, feed_dict={inputdata: image})
        preds = decoder.writer.sparse_tensor_to_str(preds[0])
        logger.info('Predict image {:s} label {:s}'.format(
            ops.split(image_path)[1], preds[0]))

        if is_vis:
            plt.figure('CRNN Model Demo')
            plt.imshow(
                cv2.imread(image_path, cv2.IMREAD_COLOR)[:, :, (2, 1, 0)])
            plt.show()
    sess.close()
Beispiel #2
0
    def __init__(self, screen):
        # Call the super constructor
        pygame.sprite.Sprite.__init__(self)

        self.screen = screen

        # Load and resize the star image
        self.image = utils.load_and_resize_image(
            "resources/star.png", (Star.STAR_SIZE, Star.STAR_SIZE))
        self.image.fill(
            self.COLOR, None,
            pygame.BLEND_MIN)  # Fill the star image with the score color

        # Set initial score at 0
        self.score = 0

        # Open the font for the score
        self.font = pygame.font.Font("resources/Bonk.ttf", 50)
Beispiel #3
0
    def switch_ball_color(self):
        image_file_path = utils.random_file_from_folder("resources/ball")

        # While the new image file is the same as the previous image, request a new one
        while image_file_path == self.image_file:
            # Get a random ball image from the ball images folder
            image_file_path = utils.random_file_from_folder("resources/ball")

        # Set the image file as the new image file path
        self.image_file = image_file_path

        # Load the ball image and resize it to it's size by the diameter + border
        self.image = utils.load_and_resize_image(
            self.image_file, (self.BALL_DIAMETER + self.BALL_BORDER,
                              self.BALL_DIAMETER + self.BALL_BORDER))

        # Get the most used color in the image and use it as the ball's color
        self.color = utils.get_dominant_color_from_image(self.image_file)
    def __init__(self, screen, image, size, y_pos):
        # Call the super constructor
        pygame.sprite.Sprite.__init__(self)

        # Save the screen as a field
        self.screen = screen

        # Set the height and the width by the sprite's size
        self.width = size[0]
        self.height = size[1]

        # Create the sprite's rect and set the sprite in the middle of the screen
        self.rect = pygame.Rect(screen.get_rect().width / 2 - self.width / 2, y_pos, self.width, self.height)

        # If an image was sent, set it
        if image is not None:
            # Load the image and resize it to the correct size
            self.image = utils.load_and_resize_image(image, (self.width, self.height))
Beispiel #5
0
from utils import load_and_resize_image, get_data, k_fold_cross_val, train_test_split_sk
from sklearn.metrics import accuracy_score

TRAIN_DIR = "images/train"
TEST_DIR = "images/test"
INPUT_SHAPE = (100, 100, 3)

# Reading the image
train_names, train_val, train_paths = get_data(TRAIN_DIR)
test_names, test_val, test_paths = get_data(TEST_DIR)

train_images = []
test_images = []

for img in train_paths:
    train_images.append(load_and_resize_image(img, INPUT_SHAPE))

for img in test_paths:
    test_images.append(load_and_resize_image(img, INPUT_SHAPE))

train_images = np.array(train_images)
test_images = np.array(test_images)
train_val = np.array(train_val)
test_val = np.array(test_val)

# Define model
model = CNNClass.Sequential(input_shape=INPUT_SHAPE)

# Convoluting the image
print("**Convolution Layer Start**")
print("**Convolution Stage**")

def parse_params():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--image_path', type=str, metavar='PATH')
    parser.add_argument('-m', '--model', type=str, metavar='PATH')
    return parser.parse_args()


if __name__ == '__main__':
    params = parse_params()
    model_file = params.model
    image_path = params.image_path
    if not exists(model_file):
        raise ValueError('{:s} doesn\'t exist'.format(model_file))
    image = load_and_resize_image(image_path)
    padded_images = np.zeros([BATCH_SIZE, 32, 100, 3])
    padded_images[:image.shape[0], :, :, :] = image
    tf.reset_default_graph()
    with tf.Session(graph=tf.Graph()) as sess:
        with gfile.FastGFile(model_file, 'rb') as f:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(f.read())
            sess.graph.as_default()
            tf.import_graph_def(graph_def, name='')
        inputdata = tf.get_default_graph().get_tensor_by_name("input:0")
        output = tf.get_default_graph().get_tensor_by_name("output:0")
        start_time = time()
        preds = sess.run(output, feed_dict={inputdata: padded_images})
        end_time = time()
        print("Recognition time: {}".format(end_time - start_time))
Beispiel #7
0
def load_images(image_path: str, files_limit: int):
    onlyfiles = [join(image_path, f) for f in listdir(image_path) if isfile(join(image_path, f))][:files_limit]
    return np.array([load_and_resize_image(p) for p in onlyfiles]), onlyfiles
def load_images(onlyfiles, files_limit: int):
    return np.array([load_and_resize_image(p) for p in onlyfiles]), onlyfiles