Exemplo n.º 1
0
Arquivo: train.py Projeto: cc07/ocr
def load_data(img_path, height=64):
    labels = []
    images = []
    images_path = []

    print('Loading images...')

    for f in listdir(img_path):
        path = join(img_path, f)

        if isfile(path) and 'jpg' in path:
            img = cv2.imread(path)
            # img = preprocess_image(img, height)
            img = resize_image(img, height)

            label = re.match(r'.*[_](.*)\.jpg', f).group(1)
            # label = label.replace('-', ' ')

            images.append(img)
            labels.append(label)

    print('Loading images...completed, total: {}/{} images'.format(
        len(images), len(labels)))

    return labels, images
Exemplo n.º 2
0
    def load_img(self, img_path, grayscale=False, from_url = False):

        if from_url == True:
            url = img_path
            #response = requests.get(url)
            #img = Image.open(BytesIO(response.content))
            ## TODO: resize image
            from skimage import io
            img = io.imread(url)

            print("removing background from image !")
            # TODO: Remove Background
            img = util.remove_background(img)

            print(img)
            print("resizing image !")
            x = util.resize_image(img)
            #img = Image.open(StringIO(response.content))
        else:
            # TODO: image should be read in grayscaled mode
            img = image.load_img(img_path, target_size=self.img_size, grayscale=grayscale)
            x = image.img_to_array(img)

        print("Expanding dims !")
        x = np.expand_dims(x, axis=0)
        print("calling preprocess_input")
        return preprocess_input(x)[0]
Exemplo n.º 3
0
def thumbnail(request: Request, id: str, timestamp: int, resize_to: int = 0):

    api = Clips()
    filepath = api.get_thumbnail(id, timestamp)
    if filepath == False:
        raise APIException(status_code=404)

    if resize_to > 0:
        with open(filepath, "rb") as handle:
            image = handle.read()
            return StreamingResponse(io.BytesIO(resize_image(image, resize_to)), media_type="image/jpeg")

    return FileResponse(filepath, media_type="image/jpeg")
Exemplo n.º 4
0
def create():
    """Create Image in Database"""
    form = PhotoForm()
    message = None
    if form.validate_on_submit():
        filename = secure_filename(form.photo.data.filename)
        name = filename[:filename.find(
            ".")]  # removes .jpg or whatever is the extension
        # form.data['photo'].seek(0)
        # data = form.data['photo'].read()  # needed to remove the extra wrapper garbage when inside Kubernetes
        image_bytes = util.resize_image(form.photo.data, (300, 300))
        # image_bytes = util.resize_image(data, (300, 300))
        if image_bytes:
            set_object(name, "faces", image_bytes)
            message = loop.run_until_complete(run("create",
                                                  name)).decode("utf-8")

    return render_template_string("""
            {% extends "main.html" %}
            {% block content %}
            <h3>Upload Photo</h3>
            <form method="POST" enctype="multipart/form-data" action="{{ url_for('create') }}">
                {{ form.csrf_token }}
                  <div class="control-group">
                   <label class="control-label">Photo</label>
                    {{ form.photo() }}
                  </div>

                   <div class="control-group">
                    <div class="controls">
                        <input class="btn btn-primary" type="submit" value="Upload">
                    </div>
                  </div>
            </form>

            {% if message %}
            <p>{{message}}</p>
            {% endif %}

            {% endblock %}
                """,
                                  form=form,
                                  message=message)
Exemplo n.º 5
0
def snapshot(request: Request, id: str, resize_to: int = 0):

    camera = request.app.camera_manager.get(id)
    if camera:
        try:
            image = camera.make_snapshot()

            if resize_to > 0:
                image = resize_image(image, resize_to)

            return StreamingResponse(io.BytesIO(image),
                                     media_type="image/jpeg")

        except Exception as e:
            log("[api] Failed to get image from stream: {}".format(str(e)))
            raise APIException(status_code=HTTP_500_INTERNAL_SERVER_ERROR,
                               detail=str(e))

    raise APIException(status_code=HTTP_404_NOT_FOUND,
                       detail="Camera not found")
Exemplo n.º 6
0
    def generate_qr(self, string_length, no_of_codes, url_base, save_location,
                    array, img_path):
        for x in range(int(no_of_codes)):
            img = ""
            rnd_string = ""
            result_string = ""
            logo = Image.open(img_path)
            logo_pos = ""

            #Generating random string via the function
            rnd_string = self.generate_string(int(string_length))

            #Concatenating the url_base, a '/' symbol and the rnd_string together, and assigning it to a var
            result_string = url_base + '/' + rnd_string

            #Creating the QR Code itself
            self.qr.add_data(result_string)
            self.qr.make(fit=True)

            #Array Generation
            self.generate_array(x, array, rnd_string)

            #Creating QR Code image with logo in center
            img = self.qr.make_image(fill_color="red",
                                     back_color="white").convert('RGB')

            logo = util.resize_image(logo, 100, 100)

            logo_pos = ((img.size[0] - logo.size[0]) // 2,
                        (img.size[1] - logo.size[1]) // 2)
            img.paste(logo, logo_pos)

            if rnd_string == "":
                img.save(save_location + '/' + 'asd' + '.png')
            else:
                img.save(save_location + '/' + rnd_string + '.png')

            #Clearing QR Code for next cycle
            self.qr.clear()
        self.call_exporter(self.exporter_arr)
Exemplo n.º 7
0
def process(s3, bucket, output_prefix, content):
    def downloader(key, output_dir):
        path = pathlib.PurePath('/tmp') / pathlib.PurePath(key).name
        s3.download_file(bucket, key, str(path))

        return path

    def uploader(name, path):
        key = pathlib.PurePath(output_prefix) / name

        with open(str(path), 'rb') as f:
            s3.upload_fileobj(f, bucket, str(key))

    try:
        img, path = read_image(downloader, content['Key'])
        img = util.resize_image(img, FIXED_SIZE, args.crop)
        write_image(uploader, path, img)

        if pathlib.Path(path).exists():
            pathlib.Path(path).unlink()

    except Exception as e:
        print(content['Key'], e)
Exemplo n.º 8
0
def myphotos():
    "login required my photos route"
    all_labels = ["No labels yet"]

    #####
    # rds exercise get list of images from database
    # now we have a user id from cognito
    #####
    s3_client = boto3.client('s3')
    photos = database.list_photos(flask_login.current_user.id)
    for photo in photos:
        photo["signed_url"] = s3_client.generate_presigned_url(
            'get_object',
            Params={
                'Bucket': config.PHOTOS_BUCKET,
                'Key': photo["object_key"]
            })

    form = PhotoForm()
    url = None
    if form.validate_on_submit():
        image_bytes = util.resize_image(form.photo.data, (300, 300))
        if image_bytes:
            #######
            # s3 excercise - save the file to a bucket
            #######
            prefix = "photos/"
            key = prefix + util.random_hex_bytes(8) + '.png'
            s3_client.put_object(Bucket=config.PHOTOS_BUCKET,
                                 Key=key,
                                 Body=image_bytes,
                                 ContentType='image/png')
            # http://boto3.readthedocs.io/en/latest/guide/s3.html#generating-presigned-urls
            url = s3_client.generate_presigned_url('get_object',
                                                   Params={
                                                       'Bucket':
                                                       config.PHOTOS_BUCKET,
                                                       'Key': key
                                                   })

            #######
            # rekcognition exercise
            #######
            rek = boto3.client('rekognition')
            response = rek.detect_labels(Image={
                'S3Object': {
                    'Bucket': config.PHOTOS_BUCKET,
                    'Name': key
                }
            })
            all_labels = [label['Name'] for label in response['Labels']]

            #######
            # rds excercise
            # added user id and description to the database
            #######
            labels_comma_separated = ", ".join(all_labels)
            database.add_photo(key, labels_comma_separated,
                               form.description.data,
                               flask_login.current_user.id)
            form.description.data = ''

    return render_template_string("""
            {% extends "main.html" %}
            {% block content %}
            <h4>Upload Photo</h4>
            <form method="POST" enctype="multipart/form-data" action="{{ url_for('myphotos') }}">
                {{ form.csrf_token }}
                  <div class="control-group">
                   <label class="control-label">Photo</label>
                    {{ form.photo() }}
                  </div>
                  <div class="control-group">
                    <label class="control-label">Description</label>
                    <div class="controls">
                    {{ form.description(class="form-control") }}
                    </div>
                  </div>
                    &nbsp;
                   <div class="control-group">
                    <div class="controls">
                        <input class="btn btn-primary" type="submit" value="Upload">
                    </div>
                  </div>
            </form>

            {% if url %}
            <hr/>
            <h3>Uploaded!</h3>
            <img src="{{url}}" /><br/>
            {% for label in all_labels %}
            <span class="label label-info">{{label}}</span>
            {% endfor %}
            {% endif %}
            
            {% if photos %}
            <hr/>
            <h4>Photos</h4>
            {% for photo in photos %}
                <table class="table table-bordered">
                <tr> <td rowspan="4" class="col-md-2 text-center"><img width="150" src="{{photo.signed_url}}" />
                    <a href="{{ url_for('myphotos_delete', object_key=photo.object_key) }}"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> delete</a>
                </td></tr>
                <tr> <th scope="row" class="col-md-2">Description</th> <td>{{photo.description}}</td> </tr>
                <tr> <th scope="row" class="col-md-2">Labels</th> <td>{{photo.labels}}</td> </tr>
                <tr> <th scope="row" class="col-md-2">Created</th> <td>{{photo.created_datetime}} UTC</td> </tr>
                </table>

            {% endfor %}
            {% endif %}


            {% endblock %}
                """,
                                  form=form,
                                  url=url,
                                  photos=photos,
                                  all_labels=all_labels)
Exemplo n.º 9
0
def home():
    """Homepage route"""
    all_labels = ["No labels yet"]
    faces = ["No faces yet"]

    #####
    # s3 getting a list of photos in the bucket
    #####
    s3_client = boto3.client('s3')
    prefix = "photos/"
    response = s3_client.list_objects(Bucket=config.PHOTOS_BUCKET,
                                      Prefix=prefix)
    photos = []
    if 'Contents' in response and response['Contents']:
        photos = [
            s3_client.generate_presigned_url('get_object',
                                             Params={
                                                 'Bucket':
                                                 config.PHOTOS_BUCKET,
                                                 'Key': content['Key']
                                             })
            for content in response['Contents']
        ]

    form = PhotoForm()
    url = None
    if form.validate_on_submit():
        image_bytes = util.resize_image(form.photo.data, (300, 300))
        if image_bytes:
            #######
            # s3 excercise - save the file to a bucket
            #######
            key = prefix + util.random_hex_bytes(8) + '.png'
            s3_client.put_object(Bucket=config.PHOTOS_BUCKET,
                                 Key=key,
                                 Body=image_bytes,
                                 ContentType='image/png')
            # http://boto3.readthedocs.io/en/latest/guide/s3.html#generating-presigned-urls
            url = s3_client.generate_presigned_url('get_object',
                                                   Params={
                                                       'Bucket':
                                                       config.PHOTOS_BUCKET,
                                                       'Key': key
                                                   })

            #######
            # rekcognition exercise
            #######
            rek = boto3.client('rekognition')
            response = rek.detect_labels(Image={
                'S3Object': {
                    'Bucket': config.PHOTOS_BUCKET,
                    'Name': key
                }
            })
            all_confidences = [
                label['Confidence'] for label in response['Labels']
            ]
            all_labels = [label['Name'] for label in response['Labels']]
            for i in range(0, len(all_labels)):
                all_labels[i] = all_labels[i] + ": " + str(
                    all_confidences[i]) + "%"

    return render_template_string("""
            {% extends "main.html" %}
            {% block content %}
            <h4>Upload Photo</h4>
            <form method="POST" enctype="multipart/form-data" action="{{ url_for('home') }}">
                {{ form.csrf_token }}
                  <div class="control-group">
                   <label class="control-label">Photo</label>
                    {{ form.photo() }}
                  </div>

                    &nbsp;
                   <div class="control-group">
                    <div class="controls">
                        <input class="btn btn-primary" type="submit" value="Upload">
                    </div>
                  </div>
            </form>

            {% if url %}
            <hr/>
            <h3>Uploaded!</h3>
            <img src="{{url}}" /><br/>
            {% for label in all_labels %}
            <span class="label label-info">{{label}}</span>
            {% endfor %}
            {% endif %}
            
            {% if photos %}
            <hr/>
            <h4>Photos</h4>
            {% for photo in photos %}
                <img width="150" src="{{photo}}" />
            {% endfor %}
            {% endif %}

            {% endblock %}
                """,
                                  form=form,
                                  url=url,
                                  photos=photos,
                                  all_labels=all_labels)
Exemplo n.º 10
0
def home():
    """Homepage route"""
    all_labels = ["No labels yet"]

    s3_client = boto3.client('s3')
    photos = database.list_photos()
    for photo in photos:
        photo["signed_url"] = s3_client.generate_presigned_url(
            'get_object',
            Params={
                'Bucket': config.PHOTOS_BUCKET,
                'Key': photo["object_key"]
            })

    form = PhotoForm()
    url = None
    if form.validate_on_submit():
        image_bytes = util.resize_image(form.photo.data, (300, 300))
        if image_bytes:
            #######
            # s3
            #######
            prefix = "photos/"
            key = prefix + util.random_hex_bytes(8) + '.png'
            s3_client.put_object(Bucket=config.PHOTOS_BUCKET,
                                 Key=key,
                                 Body=image_bytes,
                                 ContentType='image/png')

            url = s3_client.generate_presigned_url('get_object',
                                                   Params={
                                                       'Bucket':
                                                       config.PHOTOS_BUCKET,
                                                       'Key': key
                                                   })

            #######
            # rekcognition
            #######
            rek = boto3.client('rekognition')
            response = rek.detect_labels(Image={
                'S3Object': {
                    'Bucket': config.PHOTOS_BUCKET,
                    'Name': key
                }
            })
            all_labels = [label['Name'] for label in response['Labels']]

            labels_comma_separated = ", ".join(all_labels)
            database.add_photo(key, labels_comma_separated)

    return render_template_string("""
            {% extends "main.html" %}
            {% block content %}
            <h4>Upload Photo</h4>
            <form method="POST" enctype="multipart/form-data" action="{{ url_for('home') }}">
                {{ form.csrf_token }}
                  <div class="control-group">
                   <label class="control-label">Photo</label>
                    {{ form.photo() }}
                  </div>

                    &nbsp;
                   <div class="control-group">
                    <div class="controls">
                        <input class="btn btn-primary" type="submit" value="Upload">
                    </div>
                  </div>
            </form>

            {% if url %}
            <hr/>
            <h3>Uploaded!</h3>
            <img src="{{url}}" /><br/>
            {% for label in all_labels %}
            <span class="label label-info">{{label}}</span>
            {% endfor %}
            {% endif %}
            
            {% if photos %}
            <hr/>
            <h4>Photos</h4>
            {% for photo in photos %}
                <table class="table table-bordered">
                <tr> <td rowspan="4" class="col-md-2 text-center"><img width="150" src="{{photo.signed_url}}" /> </td></tr>
                <tr> <th scope="row" class="col-md-2">Labels</th> <td>{{photo.labels}}</td> </tr>
                <tr> <th scope="row" class="col-md-2">Created</th> <td>{{photo.created_datetime}} UTC</td> </tr>
                </table>

            {% endfor %}
            {% endif %}


            {% endblock %}
                """,
                                  form=form,
                                  url=url,
                                  photos=photos,
                                  all_labels=all_labels)
Exemplo n.º 11
0
import util

resized = util.get_local_images(resized=True)
with open(util.resized_check_path, "a") as f:
    for filename in util.get_local_images(resized=False):
        if filename not in resized:
            print("resize!!!", filename)
            util.resize_image(filename)
            f.write(f"{filename}\n")
Exemplo n.º 12
0
def home():
    """Homepage route"""
    all_labels = ["No labels yet"]

    #####
    # s3 getting a list of photos in the bucket
    #####
    s3_client = boto3.client('s3',
                             config=boto3.session.Config(
                                 s3={'addressing_style': 'path'},
                                 signature_version='s3v4'))
    prefix = "photos/"
    response = s3_client.list_objects(Bucket=config.PHOTOS_BUCKET,
                                      Prefix=prefix)
    print(response)
    photos = []
    if 'Contents' in response and response['Contents']:
        photos = [
            s3_client.generate_presigned_url('get_object',
                                             Params={
                                                 'Bucket':
                                                 config.PHOTOS_BUCKET,
                                                 'Key': content['Key']
                                             })
            for content in sorted(response['Contents'],
                                  key=lambda d: d['LastModified'])
        ]

    form = PhotoForm()
    url = None
    if form.validate_on_submit():
        image_bytes = util.resize_image(form.photo.data, (300, 300))
        if image_bytes:
            #######
            # s3 excercise - save the file to a bucket
            #######
            key = prefix + util.random_hex_bytes(8) + '.png'
            s3_client.put_object(Bucket=config.PHOTOS_BUCKET,
                                 Key=key,
                                 Body=image_bytes,
                                 ContentType='image/png')
            # http://boto3.readthedocs.io/en/latest/guide/s3.html#generating-presigned-urls
            url = s3_client.generate_presigned_url('get_object',
                                                   Params={
                                                       'Bucket':
                                                       config.PHOTOS_BUCKET,
                                                       'Key': key
                                                   })

    return render_template_string("""
            {% extends "main.html" %}
            {% block content %}
            <h4>Upload Photo</h4>
            <form method="POST" enctype="multipart/form-data" action="{{ url_for('home') }}">
                {{ form.csrf_token }}
                  <div class="control-group">
                   <label class="control-label">Photo</label>
                    {{ form.photo() }}
                  </div>

                    &nbsp;
                   <div class="control-group">
                    <div class="controls">
                        <input class="btn btn-primary" type="submit" value="Upload">
                    </div>
                  </div>
            </form>

            {% if url %}
            <hr/>
            <h3>Uploaded!</h3>
            <img src="{{url}}" /><br/>
            {% for label in all_labels %}
            <span class="label label-info">{{label}}</span>
            {% endfor %}
            {% endif %}
            
            {% if photos %}
            <hr/>
            <h4>Photos</h4>
            {% for photo in photos %}
                <img width="150" src="{{photo}}" />
            {% endfor %}
            {% endif %}

            {% endblock %}
                """,
                                  form=form,
                                  url=url,
                                  photos=photos,
                                  all_labels=all_labels)
Exemplo n.º 13
0
    """
    实验确定镜头焦距FOCAL_LENGTH
    单位是pixel
    """

    img_root = '../data/laser'

    focal_dis_arr = []

    print('Image height(resized): %d' % IMG_MAX_HEIGHT)
    print('dis mm: focal pix (conf)')
    print('-' * 30)
    for i, img_id in enumerate(sorted(os.listdir(img_root))):
        im_path = os.path.join(img_root, img_id)
        im = cv2.imread(im_path)
        im = resize_image(im)

        pt_pair, pt_mask, laser_mask, pt_score = segment_laser_points(im, use_bright=True)
        # show_images([im, laser_mask, pt_mask])

        if len(pt_pair) == 0:
            print('[WARNING] Laser point pair detection failed.')
            continue

        laser = Laser(pt_pair, pt_mask, laser_mask)

        real_dis = laser.POINT_DISTANCE
        pixel_dis = laser.point_pixel_dis()

        shot_dis = int(img_id.split('.')[0]) * 10.0 + 30
Exemplo n.º 14
0
    imgList = util.listImages(inDir, '.jpg')
    images = []

    print(modelFileName)

    print("Fetching symmetries ...")

    for i, img in enumerate(imgList, start=1):
        print(img + " [" + str(i) + "/" + str(len(imgList)) + "]")
        imgOut = outDir + img
        img = inDir + img
        data = image.imread(img)

        # Rezise image for decreased computation time and improved performance
        # Commenting this out will likely require different threshold parameters
        data = util.resize_image(data, resize)
        h, w, _ = data.shape
        minSize = {"h": h / 5, "w": w / 5}
        symmetries = []
        recursiveSym(data, symmetries, -1, minSize, rc)
        images.append([symmetries, data, imgOut])

    # Process images
    print("Processing symmetries ...")
    for i, img in enumerate(images, start=1):
        print("[" + str(i) + "/" + str(len(imgList)) + "]")
        symmetries = img[0].copy()
        data = img[1]
        imgOut = img[2]

        symmetries = util.placeInOrder(symmetries)