Exemplo n.º 1
0
def upscaling():
    data = json.loads(request.get_data(as_text=True))
    imgid = data['imgid']
    albumid = data['albumid']
    time = data['time']
    upscalingimg = Image.query.filter_by(id=imgid).first()
    # 对于已经处理过的情况的处理
    if ImageType(upscalingimg.action) != ImageType.ORIGIN:
        return jsonify(code=400, message='此图片为处理过的图片,请选择其他功能')
    if time=='2x':
        upscalingimg = Image.query.filter_by(action=ImageType.UPSCALE_2X.value, orig_id=imgid).first()
    else:
        upscalingimg = Image.query.filter_by(action=ImageType.UPSCALE_3X.value, orig_id=imgid).first()
    if upscalingimg != None:
        return jsonify(code=400, message='此图片已经优化过,请在该相册中查找')
    img = Image.query.filter_by(id=imgid).first()
    suffix = img.name[img.name.find('.') + 1:]
    imgContent = fdfs_client.downloadbyBuffer(img.url[len(fdfs_addr):])
    img = cv.imdecode(np.frombuffer(imgContent, np.uint8), cv.IMREAD_COLOR)
    print(img.shape)
    if time=='3x' and (img.shape[0] > 500 or img.shape[1] > 500):
        return jsonify(code=400, message='该图片尺寸较大,将无法执行放大操作,请选择其他操作')
    if time=='2x' and (img.shape[0] > 800 or img.shape[1] > 800):
        return jsonify(code=400, message='该图片尺寸较大,将无法执行放大操作,请选择其他操作')
    # 丢给线程池
    if time == '3x':
        fireEvent(EventModel(EventType.TASK, current_user.id, EntityType.IMAGE, imgid, current_user.id,
                         {'task': 'srcnn_process', 'action': ImageType.UPSCALE_3X.value, 'suffix': suffix, 'albumid': albumid,
                          'time': time}))
    elif time=='2x':
        fireEvent(EventModel(EventType.TASK, current_user.id, EntityType.IMAGE, imgid, current_user.id,
                             {'task': 'srcnn_process', 'action': ImageType.UPSCALE_2X.value, 'suffix': suffix,
                              'albumid': albumid,
                              'time': time}))
    return jsonify(code=200, message='得到的图片较大,稍后请刷新相册页面')
 def dohandler(self, eventModel):
     if eventModel.dict['task'] == 'deleteinbatch':
         task = largetaskexecutor.submit(deleteinbatch, eventModel.actorId,
                                         eventModel.entityId)
         #if task.result():
         # message = Message(-1, eventModel.entityOwnerId,'您刚刚' + eventModel.dict['action'] + '了名称为 ' + eventModel.dict['orginlname'] + ' 的相册信息和内容',MessageType.NOTICE)
         # db.session.add(message)
         # db.session.commit()
         # socketio.emit('noreadmsg', {'data': '20'})
         #print('!!!!')
     elif eventModel.dict['task'] == 'srcnn_process':
         if ImageType(
                 eventModel.dict['action']) == ImageType.SRCNN:  # 清晰化处理
             print('清晰化处理')
             task = largetaskexecutor.submit(srcnn_process,
                                             eventModel.entityId,
                                             eventModel.dict['albumid'],
                                             eventModel.entityOwnerId,
                                             eventModel.dict['action'])
         else:  # 放大处理
             print('放大处理')
             task = largetaskexecutor.submit(srcnn_process,
                                             eventModel.entityId,
                                             eventModel.dict['albumid'],
                                             eventModel.entityOwnerId,
                                             eventModel.dict['action'],
                                             eventModel.dict['time'])
Exemplo n.º 3
0
    def test_get_misc_images(self):
        """Test to ensure that the misc_images property
        returns images in the correct format.
        """
        path_one = (
            "/Users/ericmontague/sponsormatch/app/static/images/test_image_one.jpg"
        )
        path_two = (
            "/Users/ericmontague/sponsormatch/app/static/images/test_image_two.jpg"
        )
        role = TestModelFactory.create_role("Event Organizer")
        user = TestModelFactory.create_user()
        user.role = role
        venue = TestModelFactory.create_venue()

        event = TestModelFactory.create_event("Test Event", "live")
        event.user = user
        event.venue = venue
        package = TestModelFactory.create_package(price=100, available_packages=10)
        package.event = event
        image_type = ImageType(name="Misc")
        db.session.add_all([user, event, package, image_type])
        db.session.commit()

        image_type = ImageType.query.get(1)
        image_one = TestModelFactory.create_image(path=path_one, image_type=image_type)
        image_two = TestModelFactory.create_image(path=path_two, image_type=image_type)
        image_one.event = event
        image_two.event = event
        db.session.commit()

        paths = event.misc_images()
        self.assertEqual(paths[0], "images/test_image_one.jpg")
        self.assertEqual(paths[1], "images/test_image_two.jpg")
Exemplo n.º 4
0
def deploy(fake_data):
    """Run the below set of tasks before deployment."""
    # migrate database to latest revision
    upgrade()

    # create or update roles, event types, categories, and image types
    Role.insert_roles()
    EventType.insert_event_types()
    EventCategory.insert_event_categories()
    ImageType.insert_image_types()

    es_client = ElasticsearchClient(app.config["ELASTICSEARCH_URL"])
    es_client.create_index("events")
    # add fake data to the database if there isn't already fake data in the tables
    if fake_data:
        fake = FakeDataGenerator(48, 48)
        fake.add_all()
Exemplo n.º 5
0
def setup_environment(fake_data):
    """Cli command to setup the development environment. Starts up
    Elasticsearch, sets up the database and inserts fake data into
    the database if request.
    """
    app.sqlalchemy_search_middleware._elasticsearch_client.delete_index(
        Event.__tablename__)
    db.drop_all()
    db.create_all()

    # create or update roles, event types, categories, and image types
    Role.insert_roles()
    EventType.insert_event_types()
    EventCategory.insert_event_categories()
    ImageType.insert_image_types()

    # add fake data to the database
    if fake_data:
        fake = FakeDataGenerator(48, 48)
        fake.add_all()
def srcnn_process(imgid, albumid, userid, action, times=1):
    db.session.commit()
    img = Image.query.filter_by(id=imgid).first()
    if img == None:
        return False
    suffix = img.name[img.name.find('.') + 1:]
    imgContent = fdfs_client.downloadbyBuffer(img.url[len(fdfs_addr):])
    img = cv.imdecode(np.frombuffer(imgContent, np.uint8), cv.IMREAD_COLOR)
    g1 = tf.Graph()
    with tf.Session(graph=g1) as sess:
        srcnn = SRCNN(sess, "\srcnn\checkpoint\srcnn_21")
        if ImageType(action) == ImageType.SRCNN:
            print('清晰化处理')
            img = srcnn.superresolution(img)
        else:
            print('放大处理')
            print(int(times[0:1]))
            img = srcnn.upscaling(img, int(times[0:1]), True)
    img = Img.fromarray(img)
    f = BytesIO()
    img.save(f, format='PNG')
    f = f.getvalue()
    # 保存并上传数据库
    url = fdfs_addr + fdfs_client.uploadbyBuffer(f, suffix)
    imgname = url[url.rfind('/') + 1:]
    newimg = Image(imgname, url, ImageType(action), imgid, userid, -1)
    db.session.add(newimg)
    db.session.flush()
    db.session.commit()
    if albumid == None or albumid == '' or albumid == '1':
        rediskey = 'album:' + str(userid) + ':1'
    else:
        rediskey = 'album:' + str(userid) + ':' + albumid
    conn.zadd(rediskey, {newimg.id: time.time()})
    # 系统统计结果
    dictstr = conn.rpop('count')
    dict = eval(dictstr)
    dict['count'] = int(dict['count']) + 1
    conn.rpush('count', json.dumps(dict))
    return True
Exemplo n.º 7
0
def compare():
    data = json.loads(request.get_data(as_text=True))
    imgid = data['imgid']
    img = Image.query.filter_by(id=imgid).first()
    orginimg = Image.query.filter_by(id=img.orig_id).first()  # 原图
    if ImageType(img.action) == ImageType.SRCNN:
        return jsonify(code=200, message='和原图进行比较', url=orginimg.url)
    else:
        if ImageType(img.action)==ImageType.UPSCALE_2X:
            times = 2  # Upscale_2x
            eimg=Image.query.filter_by(orig_id=img.orig_id, action=ImageType.BICUBIC_UPSCALE_2X.value).first()
            if eimg!=None:
                return jsonify(code=201,url=eimg.url)
        elif ImageType(img.action)==ImageType.UPSCALE_3X:
            times = 3
            eimg = Image.query.filter_by(orig_id=img.orig_id, action=ImageType.BICUBIC_UPSCALE_3X.value).first()
            if eimg != None:
                return jsonify(code=201, url=eimg.url)
        imgContent = fdfs_client.downloadbyBuffer(orginimg.url[len(fdfs_addr):])
        orgimg = cv.imdecode(np.frombuffer(imgContent, np.uint8), cv.IMREAD_COLOR)
        with tf.Session() as sess:
            srcnn = SRCNN(sess, "../srcnn/checkpoint/srcnn_21")
            img = srcnn.upscaling(orgimg, times, False)
        img = Img.fromarray(img)
        f = BytesIO()
        img.save(f, format='PNG')
        f = f.getvalue()
        suffix = orginimg.name[orginimg.name.find('.') + 1:]
        url = fdfs_addr + fdfs_client.uploadbyBuffer(f, suffix)
        imgname = url[url.rfind('/') + 1:]
        if times==3:
            newpic = Image(imgname, url,ImageType.BICUBIC_UPSCALE_3X , orginimg.id, current_user.id, -1)
        elif times==2:
            newpic = Image(imgname, url,ImageType.BICUBIC_UPSCALE_2X , orginimg.id, current_user.id, -1)
        db.session.add(newpic)
        db.session.flush()
        db.session.commit()
        return jsonify(code=201, message='和传统放大方法进行比较', url=newpic.url)
Exemplo n.º 8
0
def ajaxdetail():
    data = json.loads(request.get_data(as_text=True))
    albumid = data['albumid']
    rediskey = 'album:' + str(current_user.id) + ':' + albumid
    imglist = []
    for imgid in conn.zrange(rediskey,
                             0,
                             sys.maxsize,
                             desc=True,
                             withscores=False,
                             score_cast_func=float):
        dict = {}
        imgid = byte2int(imgid)
        img = Image.query.filter_by(id=imgid).first()
        if ImageType(img.action) == ImageType.ORIGIN:
            proimg = Image.query.filter_by(orig_id=imgid).first()
            if proimg != None: continue
            dict['url'] = img.url
            dict['id'] = img.id
            imglist.append(dict)
        if len(imglist) == 6: break
    return jsonify(code=200, imglist=imglist, albumid=albumid)
Exemplo n.º 9
0
def index():
    if request.method == 'POST':
        content = request.values.get('dynamiccontent').strip()
        imgid = request.values.get('imgid')
        compareimgid = request.values.get('compareimgid')
        dynamic = Dynamic(content, current_user.id)
        db.session.add(dynamic)
        db.session.flush()
        db.session.commit()
        if imgid == None:
            files = request.files.getlist('dynamicimg')
            for f in files:
                filename = f.filename
                if filename == None or filename == '': break
                f = f.read()
                suffix = filename[filename.find('.') + 1:]
                url = fdfs_addr + fdfs_client.uploadbyBuffer(f, suffix)
                name = url[url.rfind('/') + 1:]
                img = Image(name, url, ImageType.ORIGIN, -1, current_user.id,
                            dynamic.id)
                db.session.add(img)
            db.session.commit()
            fireEvent(
                EventModel(EventType.DYNAMIC, current_user.id,
                           EntityType.DYNAMIC, dynamic.id, current_user.id,
                           {'detail': '/dynamic/' + str(dynamic.id)}))
        else:
            img = Image.query.filter_by(id=imgid).first()
            compareimg = Image.query.filter_by(id=compareimgid).first()
            img.dynamic_id = dynamic.id
            compareimg.dynamic_id = dynamic.id
            db.session.commit()
            fireEvent(
                EventModel(EventType.SHARE, current_user.id,
                           EntityType.DYNAMIC, dynamic.id, current_user.id,
                           {'detail': '/dynamic/' + str(dynamic.id)}))
        return redirect('/')
    else:
        imgid = request.args.get('imgid')
        if imgid == None:
            return render_template('adddynamic.html')
        else:
            content = ''
            img = Image.query.filter_by(id=imgid).first()  # 处理之后的图片
            if ImageType(img.action) == ImageType.SRCNN:
                compareimg = Image.query.filter_by(
                    id=img.orig_id).first()  # 原图
                content = '原图和系统处理过之后的图片比较'
            elif ImageType(img.action) == ImageType.UPSCALE_2X:
                compareimg = Image.query.filter_by(
                    orig_id=img.orig_id,
                    action=ImageType.BICUBIC_UPSCALE_2X.value).first()
                content = '传统的2x处理和系统SRCNN的2x处理的图片比较'
            elif ImageType(img.action) == ImageType.UPSCALE_3X:
                compareimg = Image.query.filter_by(
                    orig_id=img.orig_id,
                    action=ImageType.BICUBIC_UPSCALE_3X.value).first()
                content = '传统的3x处理和系统SRCNN的3x处理的图片比较'
            return render_template('adddynamic.html',
                                   img=img,
                                   compareimg=compareimg,
                                   content=content)
Exemplo n.º 10
0
def superresolution():
    if request.method == 'POST':
        data = json.loads(request.get_data(as_text=True))
        imgid = data['imgid']
        albumid = data['albumid']
        flag = data['flag']
        srcnnimg = Image.query.filter_by(id=imgid).first()
        if ImageType(srcnnimg.action)!=ImageType.ORIGIN:
            return jsonify(code=400, message='此图片为处理过的图片,请选择其他功能')
        srcnnimg = Image.query.filter_by(action=ImageType.SRCNN.value, orig_id=imgid).first()
        if srcnnimg != None:
            return jsonify(code=400, message='此图片已经优化过,请在该相册中查找')
        img = Image.query.filter_by(id=imgid).first()
        suffix = img.name[img.name.find('.') + 1:]
        imgContent = fdfs_client.downloadbyBuffer(img.url[len(fdfs_addr):])
        img = cv.imdecode(np.frombuffer(imgContent, np.uint8), cv.IMREAD_COLOR)
        if img.shape[0] > 1500 or img.shape[1] > 1500:
            return jsonify(code=400, message='该图片尺寸较大,执行该操作会导致内存泄漏')
        if img.shape[0] > 900 or img.shape[1] > 900:  # 大型任务,交给线程池处理
            fireEvent(EventModel(EventType.TASK, current_user.id, EntityType.IMAGE, imgid, current_user.id,
                                 {'task': 'srcnn_process', 'action': ImageType.SRCNN.value, 'suffix': suffix,
                                  'albumid': albumid}))
            if flag==True:
                return jsonify(code=203, message='请去图片所在相册查看结果')
            return jsonify(code=201, message='得到的图片较大,稍后请刷新相册页面')
        else:  # 小图片直接处理
            with tf.Session() as sess:
                srcnn = SRCNN(sess, "\srcnn\checkpoint\srcnn_21")
                img = srcnn.superresolution(img)
            img = Img.fromarray(img)
            f = BytesIO()
            img.save(f, format='PNG')
            f = f.getvalue()
            # 保存并上传数据库
            url = fdfs_addr + fdfs_client.uploadbyBuffer(f, suffix)
            imgname = url[url.rfind('/') + 1:]
            newimg = Image(imgname, url, ImageType.SRCNN, imgid, current_user.id, -1)
            db.session.add(newimg)
            db.session.flush()
            db.session.commit()
            if albumid == None or albumid == '' or albumid == '1':
                rediskey = 'album:' + str(current_user.id) + ':1'
            else:
                rediskey = 'album:' + str(current_user.id) + ':' + albumid
            conn.zadd(rediskey, {newimg.id: time.time()})
            # 系统统计
            for i in range(0,2):
                dictstr=conn.rpop('count')
                dict=eval(dictstr)
                dict['count']=int(dict['count'])+1
                conn.rpush('count',json.dumps(dict))
            if flag==True:
                return jsonify(code=203, message='请去图片所在相册查看结果')
            return jsonify(code=200, message="success srcnn")
    else:
        rediskey = 'useralbum:' + str(current_user.id)
        albumdictlist = []
        for albumid in conn.smembers(rediskey):
            dict = {}
            albumid=byte2int(albumid)
            album = Photoalbum.query.filter_by(id=albumid).first()
            dict['id'] = album.id
            dict['name'] = album.name
            albumdictlist.append(dict)
        return render_template('superresolution.html', albums=albumdictlist)