Пример #1
0
    def post(self, user, account, group_id):
        group = get_image_group_or_404(self, group_id)

        # FIXME: admins!
        if group.owner.key() != account.key():
            return render_json_response(self, {'error': 'access-denied'})

        file_name = self.request.headers['X-File-Name']
        data = self.request.body

        mime_type = mimetypes.guess_type(file_name)[0]
        if not mime_type.startswith('image/'):
            return render_json_response(self, {'error': 'wrong-file-type'})

        img = images.Image(data)

        imgdata = ImageData(data=data)
        imgdata.put()

        image = Image(file_name=file_name,
                      width=img.width,
                      height=img.height,
                      mime_type=mime_type,
                      group=group,
                      data=imgdata,
                      digest=hashlib.sha1(data).hexdigest())
        image.put()

        memcache.delete(group.memcache_key())

        return render_json_response(self, {'name': image.file_name})
Пример #2
0
    def post(self, user, account, group_id):
        group = get_image_group_or_404(self, group_id)

        # FIXME: admins!
        if group.owner.key() != account.key():
            return render_json_response(self, {"error": "access-denied"})

        file_name = self.request.headers["X-File-Name"]
        data = self.request.body

        mime_type = mimetypes.guess_type(file_name)[0]
        if not mime_type.startswith("image/"):
            return render_json_response(self, {"error": "wrong-file-type"})

        img = images.Image(data)

        imgdata = ImageData(data=data)
        imgdata.put()

        image = Image(
            file_name=file_name,
            width=img.width,
            height=img.height,
            mime_type=mime_type,
            group=group,
            data=imgdata,
            digest=hashlib.sha1(data).hexdigest(),
        )
        image.put()

        memcache.delete(group.memcache_key())

        return render_json_response(self, {"name": image.file_name})
Пример #3
0
def load_data(dataset, p=PATH.paths, input_shape=(128, 128, 3)):
    if dataset == "dataset":
        data = ImgData.CancerData(p["dataset"], input_shape)
    else:
        data = ImgData.CancerData(p["cifar10"], input_shape)
    data.load()
    # check_data(data)
    return data
Пример #4
0
def load_data(dataset, p=PATH.paths, input_shape=(128, 128, 3)):
    if dataset == "dataset":
        data = ImgData.CancerData(p["dataset"], input_shape)
    if dataset == "dataset2018":
        data = ImgData.CancerData2018(p["dataset2018"], input_shape)
    if dataset == "cifar10":
        data = ImgData.Cifar10Data(p["cifar10"], input_shape)

    data.load()
    return data
Пример #5
0
def test_image_data():
    import PATH as Path
    import models.ImageData as ImgData

    shape = (155, 220, 1)
    paths = Path.paths_local
    data = ImgData.Data(paths[0], shape)
    data.load_steel()
    x, y = data.random_batch(50, mode="train")
    print(x.shape)
    print(y)
    ImgData.show_batch(x, y)
    x, y = data.random_batch(20, mode="test")
    ImgData.show_batch(x, y)
Пример #6
0
def median(image, size_y=3, size_x=3):
    """Median(ImageData, size_y=int, size_x=int) -> ImageData()
	aplica uma máscara mediana de tamanho size_x X size_y na imagem, e 
	retorna a imagem resultante
	"""
    img = image.mtx
    if len(img.shape) == 2: img = np.expand_dims(img, axis=2)  # monochrome
    img_y, img_x = img.shape[0], img.shape[1]
    med_f = (size_x * size_y) // 2
    lmt_x, lmt_y = size_x // 2, size_y // 2
    c_chn = img.shape[2]

    r = np.zeros(img.shape, dtype=img.dtype)
    img_pd = np.pad(img, ((lmt_x, lmt_x), (lmt_y, lmt_y), (0, 0)),
                    mode='constant',
                    constant_values=0)

    for x in range(lmt_x, img_x - lmt_x):
        for y in range(lmt_y, img_y - lmt_y):
            tmp = img_pd[y - lmt_y:y + lmt_y + 1, x - lmt_x:x + lmt_x + 1]
            arr = np.dsplit(tmp, c_chn)
            r[y][x] = np.array([np.sort(s).flatten()[med_f] for s in arr])

    if c_chn == 1: r = np.squeeze(r)  #tratar monocromático
    r = np.round(np.clip(r, a_min=0,
                         a_max=255))  # clipa e arrendonda os limites
    return ImageData(mtx=r)
Пример #7
0
def convolve(image, mask):
    """ convolve(ImageData,MaskData) -> ImageData, 
  aplica uma máscara convolucional em uma imagem, e retorna a imagem resultante
  """
    if len(image.mtx.shape) == 2:
        return mono_convolve(image, mask)  #caso monocromático

    img, msk = image.mtx, mask.mtx
    img_y, img_x = img.shape[0], img.shape[1]
    msk_y, msk_x = msk.shape[0], msk.shape[1]
    c_chn = img.shape[2]
    lmt_x, lmt_y = msk_x // 2, msk_y // 2

    # criar as bordas e preencher com zeros
    img_pd = np.pad(img, ((lmt_x, lmt_x), (lmt_y, lmt_y), (0, 0)),
                    mode='constant',
                    constant_values=0)
    r = np.zeros(img.shape, dtype=img.dtype)

    # fazer a convolução
    for x in range(lmt_x, img_x - lmt_x):
        for y in range(lmt_y, img_y - lmt_y):
            # extrai a matriz centrada no pivô e convoluciona
            tmp = img_pd[y - lmt_y:y + lmt_y + 1,
                         x - lmt_x:x + lmt_x + 1] * msk
            r[y][x] = np.sum(tmp, axis=(
                0,
                1))  # salva na matriz o resultado da soma, mantendo o eixo RGB

    r = np.round(np.clip(r, a_min=0,
                         a_max=255))  # clipa e arrendonda os limites
    return ImageData(mtx=r)
Пример #8
0
 def get(self, project_url, image_shortname):
     image_shortname = image_shortname.strip().strip("/")
     project_url = project_url.strip().strip("/")
     project_data = ProjectData().all().filter("url =", project_url).get()
     if project_data is None:
         self.error(404)
     image_data = ImageData().all().filter("shortname =",
                                           image_shortname).filter(
                                               "project =",
                                               project_data).get()
     if image_data is None:
         self.error(404)
     else:
         content = """
 <h2></h2>
 <p>
   <form method="post">
     Image: <img src="/projects/%s/images/%s" /><br />
     <label>Width:</label>
     <input type="text" name="width" /><br />
     <label>Height:</label>
     <input type="text" name="height" /><br />
     <input type="submit" />
   </form>
 </p>""" % (project_data.url, image_data.shortname)
     template_values = {'title': 'Resize Image', 'content': content}
     path = os.path.join(os.path.dirname(__file__), '../../', 'template',
                         'secondary.html')
     self.response.out.write(template.render(path, template_values))
Пример #9
0
def upload():
    user_id = current_user.user_id_hash
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            extension = filename.split(".")
            extension = str(extension[1])
            name = current_user.user_id_hash
            name = name.replace("/", "$$$")
            destination = name + "orig" + "." + extension
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], destination))

            image = PIL.Image.open(
                os.path.join(app.config['UPLOAD_FOLDER'], destination))

            width, height = image.size

            #print(width, height)
            finalimagename = name + "." + extension
            basewidth = 200
            img = Image.open(
                os.path.join(app.config['UPLOAD_FOLDER'], destination))
            wpercent = (basewidth / float(img.size[0]))
            hsize = int((float(img.size[1]) * float(wpercent)))
            img = img.resize((basewidth, hsize), Image.ANTIALIAS)
            img.save(os.path.join(app.config['UPLOAD_FOLDER'], finalimagename))
            new__image = PIL.Image.open(
                os.path.join(app.config['UPLOAD_FOLDER'], finalimagename))
            width, height = new__image.size
            email = '*****@*****.**'
            password = '******'
            m = mega.login(email, password)
            os.chdir(r"uploads")
            os.remove(destination)
            file = m.upload(finalimagename)
            url_link = m.get_upload_link(file)
            #print(url_link)
            os.chdir(r"..")

            user_hashed = current_user.user_id_hash
            new_image = ImageData(user_hashed, finalimagename, url_link, width,
                                  height)
            db.session.add(new_image)
            db.session.commit()

            flash('File successfully uploaded')
            return redirect('/upload')
        else:
            flash('Allowed file types are png, jpg, jpeg, gif')
            return redirect(request.url)
    return render_template('upload.html', user=current_user)
Пример #10
0
 def get(self, project, url):
   project = project.strip().strip("/")
   project_data = ProjectData.all().filter("url =", project).get()
   if project_data is None:
     self.error(404)
   url = url.strip().strip("/")
   image = ImageData.all().filter("shortname =", url).filter("project =", project_data).get()
   if image is not None:
     self.response.headers['Content-Type'] = image.mimetype
     self.response.out.write(image.image)
   else:
     self.error(404)
Пример #11
0
 def get(self, project, url):
     project = project.strip().strip("/")
     project_data = ProjectData.all().filter("url =", project).get()
     if project_data is None:
         self.error(404)
     url = url.strip().strip("/")
     image = ImageData.all().filter("shortname =",
                                    url).filter("project =",
                                                project_data).get()
     if image is not None:
         self.response.headers['Content-Type'] = image.mimetype
         self.response.out.write(image.image)
     else:
         self.error(404)
Пример #12
0
 def post(self, project_url, image_shortname):
     image_shortname = image_shortname.strip().strip("/")
     project_url = project_url.strip().strip("/")
     project_data = ProjectData().all().filter("url =", project_url).get()
     if project_data is None:
         self.error(404)
     image_data = ImageData().all().filter("shortname =",
                                           image_shortname).filter(
                                               "project =",
                                               project_data).get()
     if image_data is None:
         self.error(404)
     resized_image = ResizedImageData()
     resized_image.image = image_data
     resized_image.shortname = image_data.shortname
     resized_image.height = self.request.get("height")
     resized_image.width = self.request.get("width")
     resized_image.data = images.resize(image_data.image,
                                        resized_image.width,
                                        resized_image.height)
def upload():
    #user_id = current_user.user_id_hash
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            extension = filename.split(".")
            extension = str(extension[1])
            name = current_user.user_id_hash
            name = name.replace("/", "$$$")
            destination = name + "orig" + "." + extension
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], destination))

            image = PIL.Image.open(
                os.path.join(app.config['UPLOAD_FOLDER'], destination))

            width, height = image.size

            #print(width, height)
            finalimagename = name + "." + extension
            basewidth = 200
            if width > 200:
                img = Image.open(
                    os.path.join(app.config['UPLOAD_FOLDER'], destination))
                wpercent = (basewidth / float(img.size[0]))
                hsize = int((float(img.size[1]) * float(wpercent)))
                img = img.resize((basewidth, hsize), Image.ANTIALIAS)
                img.save(
                    os.path.join(app.config['UPLOAD_FOLDER'], finalimagename))
                new__image = PIL.Image.open(
                    os.path.join(app.config['UPLOAD_FOLDER'], finalimagename))
                width, height = new__image.size
            os.chdir(r"uploads")
            os.remove(destination)

            access_token = 'cnX-updmdekAAAAAAAAAASkEbkYdKaLrD3o7Z7Pc7C7o7dPFnPzZmikuNdXxJI1J'
            transferData = TransferData(access_token)

            file_from = finalimagename
            file_to = '/iolcloud/' + finalimagename  # The full path to upload the file to, including the file name
            dbx = dropbox.Dropbox(access_token)

            # API v2
            transferData.upload_file(file_from, file_to)

            try:
                dbx.files_delete_v2("/iolcloud/" + finalimagename)
                transferData.upload_file(file_from, file_to)
            except:
                transferData.upload_file(file_from, file_to)

            result = dbx.files_get_temporary_link(file_to)
            name_url = result.link.replace("https:", "")
            print(name)

            #print(url_link)
            os.chdir(r"..")

            user_hashed = current_user.user_id_hash

            found_image_data = db.session.query(ImageData).filter_by(
                user_id=(user_hashed)).all()
            for row in found_image_data:
                ImageData.query.delete()
                db.session.commit()

            new_image = ImageData(user_hashed, finalimagename, name_url, width,
                                  height)
            db.session.add(new_image)
            db.session.commit()

            flash('File successfully uploaded')
            return redirect('/upload')
        else:
            flash('Allowed file types are png, jpg, jpeg, gif')
            return redirect(request.url)
    return render_template('upload.html', user=current_user)
Пример #14
0
import os
'''
# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("./data/CorrosionImages"):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(path[1])
        print(path[2])
        mypath = os.path.join(*path)
        filepath= os.path.join(mypath, file)
        print(filepath)
        print(len(path) * '---', file)

'''

import PATH as Path
import models.ImageData as ImgData

shape = (200, 200, 1)
paths = Path.paths_local
data = ImgData.Data(paths[2], shape, classes=3)
data.load()
x, y = data.random_batch(50, mode="train")
print(x.shape)
print(y.shape)

ImgData.show_batch(x, y)
# x, y = data.random_batch(20, mode="test")
# ImgData.show_batch(x, y)