Ejemplo n.º 1
0
def main():
    myImager = Imager()
    #myModel = Model()
    while True: 
        img = myImager.process_img(myImager.capture_img())
        if not img is None:
            myImager.show_img(img)
Ejemplo n.º 2
0
 def __init__(self, model_name_path, input_size, labels, num_requests=2):
     self.model = model_name_path + '.xml'
     self.weights = model_name_path + '.bin'
     self.labels = labels
     self.input_size = input_size
     self.imer = Imager(self.input_size, self.labels)
     if not os.path.exists(self.model) or not os.path.exists(self.weights):
         raise ValueError(
             'model files {} does not exist.'.format(model_name_path))
     self.plugin = IEPlugin(device='MYRIAD')
     log.info('Loading network files:\n\t{}\n\t{}'.format(
         self.model, self.weights))
     self.net = IENetwork(model=self.model, weights=self.weights)
     log.info('Preparing inputs')
     self.input_blob = next(iter(self.net.inputs))
     self.net.batch_size = 1
     log.info('Loading model to the plugin')
     self.current_request_id = 0
     self.next_request_id = 1
     self.num_requests = num_requests
     self.exec_net = self.plugin.load(network=self.net,
                                      num_requests=self.num_requests)
Ejemplo n.º 3
0
"""
rest api with flask for get birb photos, i/o users stuff, and the souls of the lost childrens

"""
from flask import Flask
from flask_restful import Resource, Api
from imager import Imager  # IGNORE THIS BULLSHIT, JUST IGNORE PLEASE
import sys
sys.path.append("..")

app = Flask(__name__)
api = Api(app)
# test
img = Imager()
files = img.get_files()


class Bot(Resource):
    def get(self, id):
        return {'msg': f"I f****d your mom {id} times"}  # change this


api.add_resource(Bot, '/img/<string:id>')

if __name__ == '__main__':
    app.run(debug=True)
Ejemplo n.º 4
0
from imager import Imager
from imager import ptest2
from os import path

if __name__ == "__main__":
    #testImage = ptest2()    #Nothing's like a trippy Einstein-pic to get things going.

    #Testing contrast method
    testImage = Imager(fid=path.normpath("images/einstein.gif"))
    bildeMedTekst = testImage.write_text().show()
Ejemplo n.º 5
0
    def __init__(self,
                 model_type,
                 model_file,
                 anchor_file,
                 num_classes,
                 input_size,
                 labels,
                 is_training=False):
        if model_type not in self.model_types:
            raise ValueError(
                'model_type can only be either \'full\' or \'tiny\'.')
        elif not model_type:
            model_type = self.model_types[0]
        self.model_type = model_type

        if not model_file:
            model_file = './data/bin/{}'.format(
                self.default_models.get(model_type))
        elif not os.path.exists(model_file):
            raise ValueError(
                'model file {} does not exist.'.format(model_file))
        self.model_file = model_file

        if '.pb' not in self.model_file:
            self.frozen_filename = '_'.join(
                ['frozen',
                 os.path.basename(self.model_file).split('.')[0]])
            self.frozen_filename = self.freeze_dir + self.frozen_filename + '.pb'

        if not input_size:
            input_size = 416
        if type(input_size) is int:
            self.input_size = input_size, input_size
        else:
            self.input_size = input_size

        self.labels = labels
        self.imer = Imager(self.input_size, self.labels)

        if os.path.exists(self.frozen_filename):
            self.defrost()
            self.input = tf.get_default_graph().get_tensor_by_name(
                'import/input:0')
            self.output = tf.get_default_graph().get_tensor_by_name(
                'import/detections/output:0')
        else:
            if not anchor_file:
                anchor_file = 'data/anchors/' + self.model_type + '.txt'
            elif not os.path.exists(anchor_file):
                raise ValueError(
                    '{} anchor file does not exist.'.format(anchor_file))
            self.anchor_file = anchor_file
            self.num_classes = num_classes
            self.is_training = is_training
            self.input = tf.placeholder(
                tf.float32, [None, self.input_size[0], self.input_size[1], 3],
                'input')
            self.model = self.tf_models[self.model_type](self.input,
                                                         self.num_classes,
                                                         self.input_size,
                                                         self.anchor_file,
                                                         self.is_training)
            with tf.variable_scope('detections'):
                self.output = self.model.graph()
            self.loader = WeightLoader(tf.global_variables('detections'),
                                       self.model_file)
            # self.sess.run(tf.global_variables_initializer())
            self.sess.run(self.loader.load_now())
            self.freeze()
Ejemplo n.º 6
0
class Yolow(object):
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)
    # sess = tf.Session()
    default_models = load_default_models()
    model_types = list(default_models.keys())
    freeze_dir = 'data/pb/'
    tf_models = {model_types[0]: Yolov3, model_types[1]: Yolov3Tiny}

    def __init__(self,
                 model_type,
                 model_file,
                 anchor_file,
                 num_classes,
                 input_size,
                 labels,
                 is_training=False):
        if model_type not in self.model_types:
            raise ValueError(
                'model_type can only be either \'full\' or \'tiny\'.')
        elif not model_type:
            model_type = self.model_types[0]
        self.model_type = model_type

        if not model_file:
            model_file = './data/bin/{}'.format(
                self.default_models.get(model_type))
        elif not os.path.exists(model_file):
            raise ValueError(
                'model file {} does not exist.'.format(model_file))
        self.model_file = model_file

        if '.pb' not in self.model_file:
            self.frozen_filename = '_'.join(
                ['frozen',
                 os.path.basename(self.model_file).split('.')[0]])
            self.frozen_filename = self.freeze_dir + self.frozen_filename + '.pb'

        if not input_size:
            input_size = 416
        if type(input_size) is int:
            self.input_size = input_size, input_size
        else:
            self.input_size = input_size

        self.labels = labels
        self.imer = Imager(self.input_size, self.labels)

        if os.path.exists(self.frozen_filename):
            self.defrost()
            self.input = tf.get_default_graph().get_tensor_by_name(
                'import/input:0')
            self.output = tf.get_default_graph().get_tensor_by_name(
                'import/detections/output:0')
        else:
            if not anchor_file:
                anchor_file = 'data/anchors/' + self.model_type + '.txt'
            elif not os.path.exists(anchor_file):
                raise ValueError(
                    '{} anchor file does not exist.'.format(anchor_file))
            self.anchor_file = anchor_file
            self.num_classes = num_classes
            self.is_training = is_training
            self.input = tf.placeholder(
                tf.float32, [None, self.input_size[0], self.input_size[1], 3],
                'input')
            self.model = self.tf_models[self.model_type](self.input,
                                                         self.num_classes,
                                                         self.input_size,
                                                         self.anchor_file,
                                                         self.is_training)
            with tf.variable_scope('detections'):
                self.output = self.model.graph()
            self.loader = WeightLoader(tf.global_variables('detections'),
                                       self.model_file)
            # self.sess.run(tf.global_variables_initializer())
            self.sess.run(self.loader.load_now())
            self.freeze()

    def set_input(self, images):
        if type(images) == str:
            self.imer.imset_from_path(images)
        else:
            self.imer.imset(images)

    def predict(self, confidence_theshold=.6, iou_threshold=.5):
        input_list = self.imer.preprocess()
        feed_dict = {self.input: input_list}
        batch_detections = self.sess.run(self.output, feed_dict)
        pred_list = predict(batch_detections, confidence_theshold,
                            iou_threshold)
        return self.imer.visualise_preds(pred_list)

    def freeze(self):
        graph_def = tf.graph_util.convert_variables_to_constants(
            sess=self.sess,
            input_graph_def=tf.get_default_graph().as_graph_def(),
            output_node_names=['detections/output'])
        if not os.path.exists(self.freeze_dir):
            os.makedirs(self.freeze_dir)
        with tf.gfile.GFile(self.frozen_filename, 'wb') as f:
            f.write(graph_def.SerializeToString())

    def defrost(self):
        print('Found frozen model {}, defrost and use!'.format(
            self.frozen_filename))
        with tf.gfile.GFile(self.frozen_filename, 'rb') as f:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def)
Ejemplo n.º 7
0
from walker import Walker
from imager import Imager

w = Walker([0, 0], [-256, 256, -256, 256])
w.random_walk()

imgGen = Imager(w)

imgGen.generate_linear_gradient("./generated/1.png")
imgGen.generate_linear_gradient("./generated/2.png",
                                mode="HSV",
                                start_color=(50, 200, 200),
                                end_color=(200, 255, 255))
imgGen.generate_linear_gradient("./generated/3.png",
                                mode="RGB",
                                bg_color=(0, 0, 0, 0),
                                start_color=(255, 0, 0, 0),
                                end_color=(0, 255, 0, 255))
imgGen.generate_linear_gradient("./generated/4.png",
                                mode="HSV",
                                bg_color=(0, 0, 0),
                                start_color=(0, 255, 255),
                                end_color=(255, 255, 255))

w.save("./generated/1.walker")
Ejemplo n.º 8
0
import datetime

# Sample usage file

name3 = 'wahrsis3'
center3 = [1724, 2592]
radius3 = 1470
relativePosition3 = np.array([0, 0, 0])
calibRot3 = np.array([[0.99555536, 0.09404159, 0.00506982],
                      [-0.09393761, 0.99541774, -0.01786745],
                      [-0.00672686, 0.01731178, 0.99982751]])
calibTrans3 = np.array([[0.00552915], [0.00141732], [0.00553584]])
longitude3 = '103:40:49.9'
lattitude3 = '1:20:35'
altitude3 = 59
wahrsis3 = Imager(name3, center3, radius3, relativePosition3, calibRot3,
                  calibTrans3, longitude3, lattitude3, altitude3)

name4 = 'wahrsis4'
center4 = [2000, 2975]
radius4 = 1665
relativePosition4 = np.array([-2.334, 101.3731, -8.04])
calibRot4 = np.array([[0.9710936, -0.23401871, 0.04703662],
                      [0.234924, 0.97190314, -0.01466276],
                      [-0.04228367, 0.02528894, 0.99878553]])
calibTrans4 = np.array([[-0.00274625], [-0.00316865], [0.00516088]])
wahrsis4 = Imager(name4, center4, radius4, relativePosition4, calibRot4,
                  calibTrans4)

images3 = [
    cv2.imread('wahrsis3/2015-10-29-12-58-01-wahrsis3-low.jpg'),
    cv2.imread('wahrsis3/2015-10-29-12-58-01-wahrsis3-med.jpg'),
Ejemplo n.º 9
0
path_lengths = []
speed1 = []
mem1 = []
speed2 = []
mem2 = []

for i in range(0, 10):
    w = Walker([0, 0], [-512, 512, -512, 512])
    start = time.time()
    w.random_walk()
    path_lengths.append(len(w.path))
    end = time.time()
    speed1.append(float(end - start))
    mem1.append(float(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2))

    imgGen = Imager(w)
    start = time.time()
    imgGen.generate_flat("./generated/benchmark.png")
    end = time.time()
    speed2.append(float(end - start))
    mem2.append(float(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2))


plt.plot(path_lengths, speed1, 'o')
plt.show()
plt.plot(path_lengths, mem1, 'o')
plt.show()
plt.plot(path_lengths, speed2, 'o')
plt.show()
plt.plot(path_lengths, mem2, 'o')
plt.show()
import json
from imager import Imager
from os import listdir, getcwd, walk
from os.path import isfile, join

inDir = input('Directories -\n{}\nInput directory: '.format(
    next(walk('.'))[1]))

myImager = Imager()
dataset = []

print('Processing data')
for picFile in [
        fileName if fileName.endswith('.jpg') else ''
        for fileName in listdir(getcwd() + '/' + inDir)
]:
    rawImg = myImager.open_img(inDir + '/' + picFile)
    procdImg = myImager.process_img(rawImg)
    if procdImg is None: continue

    #myImager.show_img(procdImg)
    dataset.append([procdImg.tolist(),
                    int(picFile.split()[0].split('.')[0])
                    ])  #picFile.split()[0]])

print('Writing to dataset file')
with open(inDir + '-dataset.json', 'w') as dsFile:
    dsFile.write(json.dumps(dataset))
print('Sucessfully wrote data set to JSON file')
Ejemplo n.º 11
0
class YolowNCS(object):
    def __init__(self, model_name_path, input_size, labels, num_requests=2):
        self.model = model_name_path + '.xml'
        self.weights = model_name_path + '.bin'
        self.labels = labels
        self.input_size = input_size
        self.imer = Imager(self.input_size, self.labels)
        if not os.path.exists(self.model) or not os.path.exists(self.weights):
            raise ValueError(
                'model files {} does not exist.'.format(model_name_path))
        self.plugin = IEPlugin(device='MYRIAD')
        log.info('Loading network files:\n\t{}\n\t{}'.format(
            self.model, self.weights))
        self.net = IENetwork(model=self.model, weights=self.weights)
        log.info('Preparing inputs')
        self.input_blob = next(iter(self.net.inputs))
        self.net.batch_size = 1
        log.info('Loading model to the plugin')
        self.current_request_id = 0
        self.next_request_id = 1
        self.num_requests = num_requests
        self.exec_net = self.plugin.load(network=self.net,
                                         num_requests=self.num_requests)

    def set_input(self, images):
        if type(images) == str:
            self.imer.imset_from_path(images)
        else:
            self.imer.imset(images)

    def predict(self,
                confidence_threshold=.5,
                iou_threshold=.4,
                async_mode=False):
        self.out_list = list()
        in_frames = self.imer.ncs_preprocess()
        for in_frame, orig_frame in zip(in_frames, self.imer.ims):
            objects = list()
            origin_im_size = orig_frame.shape[:-1]
            input_dict = {self.input_blob: in_frame}
            request_handle = self.exec_net.requests[self.current_request_id]
            if async_mode:
                next_request_id = self.current_request_id + 1
                if next_request_id == self.num_requests:
                    next_request_id = 0
            else:
                next_request_id = self.current_request_id
            self.exec_net.start_async(request_id=next_request_id,
                                      inputs=input_dict)
            if async_mode:
                self.current_request_id = next_request_id
            request_handle.wait()
            pred_dict = request_handle.outputs
            for layer_name, out_blob in pred_dict.items():
                params = self.net.layers[layer_name].params
                layer_params = YoloV3Params(params, out_blob.shape[2])
                objects += parse_yolo_region(out_blob, in_frame.shape[2:],
                                             origin_im_size, layer_params,
                                             confidence_threshold)
            for i in range(len(objects)):
                if objects[i]['confidence'] == 0:
                    continue
                for j in range(i + 1, len(objects)):
                    if intersection_over_union(objects[i],
                                               objects[j]) > iou_threshold:
                        objects[j]['confidence'] = 0

            objects = [
                obj for obj in objects
                if obj['confidence'] >= confidence_threshold
            ]
            self.out_list.append(objects)
        out_frames = self.imer.ncs_visualise_preds(self.out_list)
        return out_frames

    def get_output(self):
        try:
            return self.out_list
        except:
            raise ValueError(
                'output does not exist, YolowNCS.predict() method must be called prior to this method.'
            )
Ejemplo n.º 12
0
def main():

    img = Imager("pepe")

    img = img.deep_fry(0.75)

    img.display()

    img.save("memes", "")

    exit()

    t0 = time()

    ting1 = Imager("fibonacci")
    ting2 = Imager("fisheggs")
    ting3 = Imager("trail").saturation(1.2).contrast(1.1)

    w = 900; h = 550
    canvas = Imager(w = w, h = h, bg = (255, 192, 192))
    canvas = canvas.fill(ting3)

    
    _ting2 = ting2.scale(0.2).saturation(1.3)
    _ting2_w, _ting2_h = _ting2.get_dims()
    y_offset = h // 2 - _ting2_w // 4

    for i in range(w // _ting2_w + 1):
        for j in range(1):
            canvas._paste(_ting2.pixelate(0.1 + i / (w // _ting2_w)), pos = (i * _ting2_w, y_offset))
    
    _ting1 = ting1.scale(0.05).saturation(2)

    from math import sin
    fn = lambda x: int(200 * sin(x / 8))

    
    for i in np.linspace(-75, 75, 300):
        canvas.splice(_ting1.saturation(0 + rand()).rotate(rand() * 90), alpha = 2/3, pos = (int(5 * i), fn(i)))

    #canvas = canvas.deep_fry(intensity = 1) # intensity in (0, 1.5)

    #canvas = canvas.collage(ting1, Imager.scale, 0.5)

    t1 = time()

    print("Image generation took: ", (t1-t0)*1000, "ms")

    canvas.display()

    canvas.img.convert("RGB")
    canvas.save("some file name", "", ext = "png") # "" saves to "root" director
Ejemplo n.º 13
0
from imager import Imager
from imager import ptest2
from os import path

if __name__ == "__main__":
    #testImage = ptest2()    #Nothing's like a trippy Einstein-pic to get things going.

    #Testing contrast method
    testImage = Imager(fid=path.normpath("images/einstein.gif"))
    testImage.equalize().display()