예제 #1
0
 def test_delete_image(self):
     test_image = Image("test.jpg")
     test_image.save_image()
     test_image2 = Image("test.jpg")
     test_image2.save_image()
     test_image.delete_image()
     self.assertEqual(len(Image.image_list), 1)
예제 #2
0
    def segment_as_predict(self, img, debug=False):
        image = Image(img.copy())
        for j in range(len(image.fields)):  # constant 5
            for k in range(len(image.fields[j].spans)):  # constant 2-3
                _, width = image.fields[j].spans[k].image.shape[:2]

                image.fields[j].spans[k].predict_segments = []

                for s in range(0, width, SLIDE):
                    end = s + WIDTH - 1
                    if end > width - 1:  # the end of the window exceed the end of the span
                        break
                    im = image.fields[j].spans[k].image[:, s:end]
                    X = self._img_to_X(im)
                    pred = self._predict(X)
                    if pred == 1:
                        middle = int((s + end) / 2)
                        image.fields[j].spans[k].predict_segments.append(
                            middle)

        if debug:
            debug_img = Image(img.copy())
            for j in range(len(debug_img.fields)):  # constant 5
                for k in range(len(debug_img.fields[j].spans)):  # constant 2-3
                    for s in image.fields[j].spans[k].predict_segments:
                        debug_img.fields[j].spans[k].image[:, s] = [0, 0, 255]
            merged_img = debug_img.merge_fields()
            cv2.imwrite('segments_as_predict.png', merged_img)
        return image
예제 #3
0
	def __init__(self, img_folder):
		self.images = []

		names = os.listdir(img_folder)
		for n in names:
			img = cv2.imread(img_folder + n)
			self.images.append(Image(img, n))
예제 #4
0
def index(request):
    # Handle file upload
    face_img_urls = []
    face_dir = settings.FACE_CROP_IMAGE_DIR.split(os.sep)[-1]

    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        current_images = Image.objects.all()
        new_id = len(current_images) + 1
        files = request.FILES.getlist('img')
        for file_i in range(len(files)):
            newdoc = Image(docfile=files[file_i])
            new_file_name = str(new_id + file_i) + os.path.splitext(
                files[file_i].name)[1]
            newdoc.docfile.name = new_file_name
            newdoc.save()
            face_file_paths = face_detection.detect_one_img(
                settings.UPLOAD_IMAGE_DIR + os.sep + new_file_name,
                settings.FACE_CROP_MARGIN, settings.FACE_CROP_IMAGE_DIR)
            face_urls = []
            for face_name in face_file_paths:
                face_name = face_name.split(os.sep)
                _url = settings.MEDIA_URL + face_dir + os.sep + face_name[-1]
                face_urls.append(_url)
            face_img_urls.append(face_urls)
        # Load documents for the list page
    else:
        form = ImageForm()  # A empty, unbound form

    return render_to_response("list.html", {
        'face_img_urls': face_img_urls,
        'form': form
    },
                              context_instance=RequestContext(request))
예제 #5
0
def upload_image (data, request):
    '''Upload image to BAE cloud storage.'''
    '''@receive FormData "username": string, "allowOverwrite": boolean, "images" : <files in request.FILES>'''
    '''@return JSON indicating saved images, format [{'name':filename, 'path':imageSavePath}].'''
    methodName = 'uploadImage'
    username = request.user.username
    allowOverwrite = request.POST.get('allowOverwrite')
    savedImgs = []

    for img in request.FILES.getlist('images'):
        imgSavePath = resourcesHelper.getFileSavePath(username, img.name)
        imgSaveName = img.name[:img.name.rfind('.')]

        if bosResource.upload_by_str(imgSavePath, img.read()):     # Upload file succeeds. Save record to database.
            imgInfo = {'name':imgSaveName, 'path':imgSavePath}
            savedImgs.append(imgInfo)
            existedImages = Image.objects.filter(username=username, name=imgSaveName)
            if len(existedImages) == 0:     # New Record.
                Image(username=username, name=imgSaveName, src=imgSavePath).save()
            elif allowOverwrite is not None:    # Update existing record. There will be only one record as unique_together Meta setting.\
                existedImage = existedImages[0]
                existedImage.src = imgSavePath
                existedImage.save()
                imgInfo['overwrite'] = True
            else:
                raise E.JsonRequestException(EnumErrorCodes.OverwriteNotAllowed, 'Attempt to overwrite existed image with name (%s) while not allow to overwrite.' % imgSaveName)
        else:
            raise E.BAEException('%s: Saving image to BAE bucket failed. Image name:%s. Error info: %s' % (methodName, img.name, response))

    return savedImgs
예제 #6
0
파일: cragapp.py 프로젝트: nixorn/cl_poster
def upload_images():

    if request.method == 'POST':
        idads = request.form['idads']
        images = request.files.getlist('images[]')

        for image in images:
            if image and allowed_file(image.filename):
                extension = image.filename.split('.')[-1]
                if extension == "jpg": mime = "image/jpeg"
                else: mime = "image/" + extension
                i = Image(idads=idads,
                          extension=extension,
                          mime=mime,
                          filename=image.filename,
                          image=image.read())
                db_session.add(i)
                try:
                    db_session.commit()

                except:
                    db_session.rollback()
                    raise Exception('DB commit is not OK')

    return "Images uploaded?"
예제 #7
0
    def post(self):
        stream_id = self.request.get('stream_id')
        template = JINJA_ENVIRONMENT.get_template('error.html')

        data = {}
        if not Stream.get_by_id(stream_id):
            data['msg'] = 'Stream id %s not found!' % stream_id
            return self.response.write(template.render(data))
        if not self.request.get('files[]'):
            data['msg'] = 'Hey, Upload an image first!'
            return self.response.write(template.render(data))

        results = []
        for img in self.request.get_all('files[]'):
            results.append({'name': '', 'url': '', 'type': '', 'size': 64})
            avatar = images.resize(img, 320, 320)
            lat = self.request.get('lat')
            lat = float(lat) if lat else None
            lng = self.request.get('lng')
            lng = float(lng) if lng else None
            image = Image(data=db.Blob(avatar),
                          comment=self.request.get('comment'),
                          lat=lat,
                          lng=lng).put()
            Stream.append_image(stream_id, image)
        s = json.dumps({'files': results}, separators=(',', ':'))
        self.response.headers['Content-Type'] = 'application/json'
        return self.response.write(s)
예제 #8
0
def upload():
    '''
    print request.files
    print type(request.files)
    print dir(file)
    打印看一下文件的目录信息,文件信息等,在后面提取关键字的时候使用。比如有如下信息:
    ['__bool__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__',
    '__hash__', '__init__', '__iter__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__',
    '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parse_content_type', 'close',
    'content_length', 'content_type', 'filename', 'headers', 'mimetype', 'mimetype_params', 'name', 'save', 'stream']
    '''
    # 1.将上传的文件的信息通过request请求获取出来,保存在变量file中;files是请求提交过来时里面的一些文件;
    # []内是上传的文件定义的key名字。如果上传的多变量,比如还有file1,file2等,直接在这个dict里更改即可,可以提取file1,file2.
    file = request.files['file']
    # 2.将文件后缀名取出存入file_ext变量中;
    file_ext = ''
    if file.filename.find('.') > 0:
        file_ext = file.filename.rsplit(
            '.', 1)[1].strip().lower()  # 比如为xxx.bmp,则file_ext内容为bmp
    # 3.将图片提交至服务器之前,先对文件的后缀名做一个验证,看后缀名是否在配置文件允许范围之内;若符合,则将文件保存在服务器,并获得一个URL地址
    if file_ext in app.config['ALLOWED_EXT']:
        # 获得文件整体名字,为了防止名字中含有html等干扰信息,选择用一个uuid(通用唯一识别码,就是一个随机值)的方式代替真名字
        file_name = str(uuid.uuid1()).replace('-', '') + '.' + file_ext
        # url = save_to_local(file, file_name)  # 调用写好的函数,将文件保存在本地,并获得一个URL地址
        url = save_to_qiniu(file, file_name)  # 调用写好的函数,将文件保存在服务器,并获得一个URL地址
        # 4.如果URL存在,则将该图加载到数据库当中
        if url != None:
            db.session.add(Image(url, current_user.id))
            db.session.commit()
    # 5.如果上面某几步失败或者全部执行完后,将跳转回当前上传图片的用户的个人详情页去
    # return redirect('/profile/%d/' % current_user.id)
    return redirect_with_msg('/profile/%d/' % current_user.id,
                             '图片上传成功')  # 打一个flash消息
예제 #9
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})
예제 #10
0
파일: api.py 프로젝트: kugooer/nazurin-1
 def getImages(self, post):
     """Get images from post."""
     url = post['file_url']
     filename = 'gelbooru - ' + post['image']
     imgs = list()
     imgs.append(Image(filename, url))
     return imgs
예제 #11
0
def show_or_return(path):
    i = Image(path)
    if show:
        i.show_image()
    else:
        i.detect_face()
        return i.face_matrix, i.rect
예제 #12
0
def new_image_hololens():
    username = request.form['username']
    password = request.form['password']

    if not username or not password:
        return jsonify({"msg":
                        "Missing login parameter"}), Status.HTTP_BAD_REQUEST
    if 'image' not in request.files:
        return jsonify({"msg": "Missing image"}), Status.HTTP_BAD_REQUEST
    new_im = request.files['image']
    caption = ""
    if "caption" in request.form:
        caption = request.form["caption"]
    name = new_im.filename

    if Image.query.filter(Image.name == name).first():
        new_name = find_new_name(name)
        if new_name == name:
            return jsonify({
                "msg":
                "Filename already exists, and server is unable to find a new name"
            }), 500
        else:
            name = new_name

    m = hashlib.new('sha512')
    m.update(password.encode('utf-8'))
    password = m.hexdigest()
    registered_user = User.query.filter(User.username == username,
                                        User.password == password).first()
    if not registered_user:
        return jsonify({"msg": "Invalid login"}), Status.HTTP_BAD_REQUEST

    if not name or name == '' or len(name) > 50:
        return jsonify({"msg": "File must have a valid name"
                        }), Status.HTTP_BAD_REQUEST

    path_to_image = os.path.join(image_dir, name)
    fw = open(path_to_image, 'wb')
    fw.write(new_im.read())
    fw.close()

    db.session.add(
        Image(name=name,
              owner=username,
              path_to_image=path_to_image,
              caption=caption))
    db.session.commit()

    added_image = Image.query.filter(Image.name == name).first()
    if not added_image:
        return jsonify({"msg": "Error adding image to server"}), 500

    return jsonify({
        "msg":
        "Successfully added image",
        "url":
        "https://screenshot-tool-eecs498.herokuapp.com/details?image_id=" +
        str(added_image.id)
    }), Status.HTTP_OK_BASIC
예제 #13
0
 def test_create_image(self):
     i = Image(slug="broom", icon_set="fugue", path="icons/fugue/broom.png")
     i.put()
     self.assertEquals(i.slug, "broom")
     self.assertEquals(i.icon_set, "fugue")
     self.assertEquals(i.path, "icons/fugue/broom.png")
     self.assertEquals(i.absolute_url(), "/images/icons/fugue/broom.png")
예제 #14
0
def createImageModelList(images=[]):
    image_model_List = []

    euca_metadata = EucalyptusMetadataDB()
    image_snapshot_list = euca_metadata.getImageSnapshotList()

    for image in images:
        if not Image.objects.filter(image_id=image.id):
            new_image = Image()
            new_image.image_id = image.id
            new_image.name = "新しいOSイメージ"
            new_image.description = ""
            new_image.save()
            logger.debug('新しいOSイメージを登録しました: %s' % image.id.encode('utf8'))

    for image in images:
        if image.type == "machine":
            #(account_id, owner) = getUserFromImage(image)
            #logger.debug("account_id:%s owner:%s" % (account_id, owner))
            image_model = euca_common.createImageModel(images, image.id)
            if image_model != None:
                if image_model.root_device_type == "ebs":
                    for snap in image_snapshot_list:
                        if snap.image_id == image_model.id:
                            image_model.image_snapshot = snap.snapshot_id
                            break
                image_model_List.append(image_model)

    return image_model_List
예제 #15
0
파일: api.py 프로젝트: kugooer/nazurin-1
    def parsePost(self, post):
        """Get images and build caption."""
        # Get images
        url = post['file_url']
        artists = post['tag_string_artist']
        title, filename = self._getNames(post)
        imgs = list()
        imgs.append(Image(filename, url))

        # Build media caption
        tags = post['tag_string'].split(' ')
        tag_string = str()
        for character in tags:
            tag_string += '#' + character + ' '
        details = dict()
        if title:
            details['title'] = title
        if artists:
            details['artists'] = artists
        details.update({'url': 'https://' + self.site + '.donmai.us/posts/' + str(post['id']), 'tags': tag_string})
        if post['parent_id']:
            details['parent_id'] = post['parent_id']
        if post['pixiv_id']:
            details['pixiv_id'] = post['pixiv_id']
        if post['has_children']:
            details['has_children'] = True
        return imgs, details
예제 #16
0
def upload():
    #print type(request.files)
    #print request.files
    file = request.files['file']
    #print dir(file)
    file_ext = ''
    if file.filename.find('.') > 0:
        file_ext = file.filename.rsplit('.')[1].strip().lower()
    if file_ext in app.config['ALLOWED_EXT']:
	file_name = str(uuid.uuid1()).replace('-','')+'.'+file_ext
        
	
	#current_user#
        if not current_user.is_authenticated:
	    return 'None'#current_user.is_authenticated # ,current_user.name
	#current_user#


	#url = save_to_local(file,file_name)
	url = qiniu_upload_file(file,file_name)
	

        if url != None:
	    db.session.add(Image(url,current_user.id))
	    db.session.commit()
        
    return redirect('/profile/%d' % current_user.id)
    return 'OK'
예제 #17
0
def adddog():
    '''
    Post page
    '''
    form = PostForm()
    if request.method == 'POST' and form.validate_on_submit():

        new = Post(title=form.title.data,
                   text=form.post.data,
                   user=current_user,
                   gender=form.gender.data,
                   age=form.age.data)
        for split in form.tags.data.split(' '):
            tag = Tag.query.filter_by(tag_name=split).first()
            if tag is not None:
                new.tags.append(tag)

        images = request.files.getlist("upload")
        for img in images:
            ext = img.filename.split(".")[1]
            filename = str(int(time.time() * 1e6) +
                           randint(300, 43242)) + '.' + ext
            image_file = os.path.join(APP.config['UPLOAD_FOLDER'], filename)
            img.save(image_file)
            new.images.append(Image(name=filename))

        DB.session.add(new)
        DB.session.commit()
        return redirect(url_for('index'))
    return render_template('post.html', form=form, tags=TAGS)
예제 #18
0
    def create_image():
        if 'file' not in request.files:
            abort(400)

        file = request.files['file']

        if file.filename == '':
            abort(400)

        if file and allowed_file(file.filename):
            try:
                filename = secure_filename(file.filename)
                filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                filetype = filename.split(".")[-1]
                file.save(filepath)

                image = Image(filepath, filename, filetype)
                image.insert()

                return jsonify({
                    'success': True,
                    'image': image.format()

                })
            except BaseException:
                abort(422)
예제 #19
0
    def __init__(self, img_folder, segmap_folder, at, to):
        self.images = []

        names = os.listdir(img_folder)
        self.at = at
        if to:
            self.to = to + 1
        else:
            self.to = len(names)

        for i in range(self.at, self.to):
            img = cv2.imread(img_folder + names[i])
            image = Image(img, names[i])

            # read segmap into image's span object
            base = names[i].split('.')[0]
            with open(segmap_folder + base, 'r') as m:
                text = m.read().strip()
            text = text.split('\n')
            f_idx = 0
            s_idx = 0
            for i in range(len(text)):
                if text[i] != "":
                    l = [int(x) for x in text[i].split()]
                    image.fields[f_idx].spans[s_idx].segcols = l
                    s_idx += 1

                else:
                    f_idx += 1
                    s_idx = 0

            self.images.append(image)
예제 #20
0
def create():
    file = request.files.get("image")
    if file.filename:
        url = upload(file)
        image = Image(url=url, user_id=current_user.id)
        image.save()
    return redirect(url_for('users.show', username=current_user.username))
예제 #21
0
파일: main.py 프로젝트: vlaght/arkashe
def fill_data():
    fake = Faker()
    db = SessionMaker()
    users = [
        User(login=fake.email(),
             posts=[
                 Post(
                     title=fake.sentence(),
                     body=fake.text(),
                 ) for _ in range(random.randint(3, 7))
             ]) for _ in range(random.randint(5, 15))
    ]
    images = [
        Image(url=fake.image_url()) for _ in range(random.randint(50, 100))
    ]
    db.add_all(users)
    db.add_all(images)
    db.commit()

    post_ids = [p[0] for p in db.query(Post.id).all()]
    image_ids = [i[0] for i in db.query(Image.id).all()]
    secondary_records = []
    for post_id in post_ids:
        chosen_image_ids = random.sample(image_ids, k=random.randint(1, 10))
        for image_id in chosen_image_ids:
            secondary_records.append(
                ImagePost(post_id=post_id, image_id=image_id))
    db.add_all(secondary_records)
    db.commit()
예제 #22
0
def create_image():

    # create image from url
    url = request.json['url']

    # Check if the image url exist
    existing_image = (Image.query.filter(Image.url == url).one_or_none())

    if existing_image is None:
        # Insert image to the first step of the image
        schema = ImageSchema()
        new_image = Image(url=url)

        # Save to the database
        db.session.add(new_image)
        db.session.commit()

        # Serialize and return the newly created data in the response
        data = schema.dump(new_image)

        return jsonify(data), 201

    # Otherwise, nope, data exists already
    else:
        abort(400, "Image url already exists: {url} ".format(url=url))
예제 #23
0
def handleImagePopAdd(request,
                      addForm,
                      field,
                      template="form/popmediaadd.html"):
    if not request.method == "POST":
        f = UploadForm()
        ctx = {'form': f, 'field': field}
        return render(request, template, ctx)

    f = UploadForm(request.POST, request.FILES)

    if not f.is_valid() and not request.FILES['file'].name.endswith('.svg'):
        ctx = {'form': f, 'field': field}
        return render(request, template, ctx)
    file = request.FILES['file']
    store_in_s3(file.name, file.read())
    p = Image(url="http://%s.s3.amazonaws.com/%s" % (bucket, file.name))

    if isinstance(request.user, AnonymousUser):
        p.user = User.objects.get(username="******")
    else:
        p.user = User.objects.get(username=request.user)
    if request.POST['artist']:
        p.artist = User.objects.get(pk=request.POST['artist'])
    p.save()
    newObject = p

    # Self destruction:
    if newObject:
        return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' %\
            (escape(newObject._get_pk_val()), escape(newObject)))
예제 #24
0
def imageAdd():
    url = request.values['url']
    user_id = int(request.values['user_id'])
    image = Image(url, user_id)
    db.session.add(image)
    db.session.commit()
    return json.dumps({"code": 0, "id": image.id})
예제 #25
0
def ParseGraphVRD(d):
    image = Image(d['photo_id'], d['filename'], d['width'], d['height'], '',
                  '')

    id2obj = {}
    objs = []
    rels = []
    atrs = []

    for i, o in enumerate(d['objects']):
        b = o['bbox']
        obj = Object(i, b['x'], b['y'], b['w'], b['h'], o['names'], [])
        id2obj[i] = obj
        objs.append(obj)

        for j, a in enumerate(o['attributes']):
            atrs.append(Attribute(j, obj, a['attribute'], []))

    for i, r in enumerate(d['relationships']):
        s = id2obj[r['objects'][0]]
        o = id2obj[r['objects'][1]]
        v = r['relationship']
        rels.append(Relationship(i, s, v, o, []))

    return Graph(image, objs, rels, atrs)
예제 #26
0
def upload_file():
    if request.method == 'POST':

        if 'image' in request.files:
            image = request.files['image']

            if allowed_file(image.filename):
                image.save(
                    os.path.join(app.config['IMAGE_UPLOADS'], image.filename))
                title = request.form.get('title')
                filename = image.filename

                db_image = Image(title, filename)
                if 'tag' in request.form:
                    tags = request.form.getlist('tag')
                    tag_list = Tag.query.filter(Tag.tag_name.in_(tags))

                    for tag in tag_list:
                        db_image.tags.append(tag)

                db.session.add(db_image)
                db.session.commit()

                return redirect(url_for('index'))
            return 'no image found!'

        else:
            return "No image uploaded!"
예제 #27
0
def upload_qiniu(upload_file):
    '''七牛图片上传'''
    img = Image(upload_file.filename)
    img.url = utils.upload_img(img.filename, upload_file.read())
    db.session.add(img)
    db.session.commit()
    return img.url
예제 #28
0
파일: apis.py 프로젝트: D-Cup/study
 def post(self):
     args = self.parser.parse_args()
     img = Image()
     img.name = args['name']
     img.url = args['url']
     add(img)
     return {'msg': '添加图片成功'}
예제 #29
0
def save_image_to_post(errors, form, args):
    """Save images

    Save image from form and return errors

    :param form:
    :param args:
    :param errors:
    :return: errors
    """
    # vars
    args["upload_folder"] = app.config["UPLOAD_FOLDER_POST"]
    args["user_id"] = False

    # all images
    images = form.images.data

    for file in images:

        # VALIDATE
        if file.filename == "":
            continue

        if not (file and allowed_file(file.filename)):
            errors.append("img {} hav a invalid format".format(file.filename))
            return errors

        # SAVE
        args["image_record"] = Image(post_id=args["post_id"])
        errors = (save_img_body(errors, file, args))

    return errors
예제 #30
0
def upload():
    """Upload image from passed URL."""

    # Validate is image URL.
    request_data = request.get_json()
    if request_data is None or request_data.get('image_url', None) is None:
        return build_response('Request data invalid or Image URL not found.', 400)

    image_url = request_data.get('image_url')
    if not is_url_valid(image_url):
        return build_response('Image URL not valid.', 400)

    # Download image from URL.
    image_bytes = download_image_from_url(image_url)
    if image_bytes is None:
        return build_response('Unable to download image from URL, try again.', 400)

    # Upload image to servers and add to cache.
    try:
        image_name = image_url[image_url.rfind('/') + 1 :]
        image = Image(image_bytes, image_name)
        image.save()
    except ImageNotValidException as e:
        return build_response(f'Image validation error: {e.error}', 400)
    except ImageUploadException:
        return build_response('Unable to upload image to server', 500)

    # Return new image URL
    image_url = url_for(endpoint='view', image_name=image_name, _external=True)
    return build_response('Image uploaded successfully', 201, data={'image_url': image_url})