Example #1
0
 def test_create_request_correctly(self):
     session_id = 'sessionId'
     requester = Requester('login', 'pw', 'first', 'last',
                           '5f81ae776db502d353a84fdf')
     self.requester_handler.active_user_sessions[session_id] = requester
     item_1 = Item('item1', 42.42, 'category', '5f7c28c6e979c6a33a1f3f79',
                   ProductDetails('', {}), Image('', ''))
     item_2 = Item('item2', 13.37, 'category', '5f7c28c6e979c6a33a1f3f79',
                   ProductDetails('', {}), Image('', ''))
     item_1_id = self.items_dao.store_one(item_1.to_db_object())
     item_2_id = self.items_dao.store_one(item_2.to_db_object())
     item_1_amount = 5
     item_2_amount = 3
     request_items = [{
         'id': item_1_id,
         'amount': item_1_amount
     }, {
         'id': item_2_id,
         'amount': item_2_amount
     }]
     request_id = self.request_handler.create_request(
         request_items, session_id)
     requests = self.requests_dao.get_all()
     self.assertEqual(len(requests), 1)
     self.assertEqual(str(requests[0]['_id']), request_id)
     self.assertEqual(str(requests[0]['requester']), requester.id)
     self.assertEqual(requests[0]['volunteer'], None)
     self.assertEqual(requests[0]['status'], RequestStatus.CREATED)
     self.assertEqual(str(requests[0]['items'][0]['id']), item_1_id)
     self.assertEqual(requests[0]['items'][0]['amount'], item_1_amount)
     self.assertEqual(str(requests[0]['items'][1]['id']), item_2_id)
     self.assertEqual(requests[0]['items'][1]['amount'], item_2_amount)
Example #2
0
    def get_image_summary_info(self, user):
        dev_observed = Device_Observed()
        res = {
            'user_name': user.name,
            'device_counts': dev_observed.count_user_devices(user.id),
            'device_info': []
        }
        devices = dev_observed.observed_devices(user.id)
        print devices
        pos = Position_Image()
        for dev in devices:
            contents_dev = {}
            print dev
            contents_dev['location'] = dev.location
            contents_dev['position_contents'] = []
            positions = pos.get_position_by_device_id(dev.id)
            if positions:
                for pos in positions:
                    img = Image()
                    image_count = img.count_by('where position_id = ?', pos.id)
                    contents_dev['position_contents'].append({
                        'position':
                        pos.position,
                        'duration':
                        pos.duration,
                        'image_count':
                        image_count,
                        'object_name':
                        pos.object_name
                    })
            res['device_info'].append(contents_dev)

        return res
Example #3
0
 def test_get_items_by_shop_and_category(self):
     dao = ItemsDAO(self.db)
     category_a = 'CategoryA'
     category_b = 'CategoryB'
     shop_a = '5f7c28c6e979c6a33a1f3f79'
     shop_b = '5f7c2d96e48e242b81178822'
     item_1 = Item('Name1', 1.0, category_a, shop_a, ProductDetails('', {}),
                   Image('', ''))
     item_2 = Item('Name2', 1.0, category_a, shop_b, ProductDetails('', {}),
                   Image('', ''))
     item_3 = Item('Name3', 1.0, category_b, shop_a, ProductDetails('', {}),
                   Image('', ''))
     item_4 = Item('Name4', 1.0, category_b, shop_b, ProductDetails('', {}),
                   Image('', ''))
     for item in [item_1, item_2, item_3, item_4]:
         dao.store_one(item.to_db_object())
     items = self.item_handler.get_items_by_shop_and_category(None, None)
     self.assertEqual(len(items), 4)
     items = self.item_handler.get_items_by_shop_and_category(
         shop_a, category_a)
     self.assertEqual(len(items), 1)
     self.assertEqual(items[0]['name'], item_1.name)
     items = self.item_handler.get_items_by_shop_and_category(shop_b, None)
     self.assertEqual(len(items), 2)
     self.assertEqual(len([i for i in items if i['name'] == item_2.name]),
                      1)
     self.assertEqual(len([i for i in items if i['name'] == item_4.name]),
                      1)
     items = self.item_handler.get_items_by_shop_and_category(
         None, category_b)
     self.assertEqual(len([i for i in items if i['name'] == item_3.name]),
                      1)
     self.assertEqual(len([i for i in items if i['name'] == item_4.name]),
                      1)
def img_upload(device_mac, device_pos,created_at, meta):
    if device_mac == "":
        return False

    if device_pos == "":
        return False
    dev = Device()
    pos = Position()
    #print "upload_img",device_mac,device_pos

    device_id = dev.get_device_by_mac(device_mac)
    position_id = pos.get_position_id(device_id, device_pos)
    print "upload",device_id,position_id
    upload_path = os.path.join(getPWDDir(), CAPTURED_DIR)
    filename = meta['filename']
    filename = os.path.basename(filename)
    print filename,'----',upload_path

    filepath = os.path.join(upload_path, filename)
    with open(filepath, 'wb') as up:
        up.write(meta['body'])

    img = Image()
    img.path = filename
    img.position_id = position_id
    img.created_at = created_at
    img_id = img.create()
    print img_id
    if not img_id:
        return False
    return True
Example #5
0
def image_create():
    json = request.get_json()
    newImage = Image(dict=json)
    newImage = ctrImage.create(newImage)
    if newImage is None:
        return jsonify({}), 404
    else:
        for tag in newImage.getTagList():
            adiTag = ctrAdiTag.getByTagDictionary(formats.parseAdiTag(tag))
            #print(tag + " => " + adiTag.)
            if adiTag is not None:
                ctrImage.addTag(newImage, adiTag)
        return jsonify(newImage.serialize()), 201
    def _get_checksum_content(self):
        checksum_path_path = f"{self.dir_getter.backups_dir()}/{self.secondary_backup_id}/checksum.txt"
        checksum_path_content = None
        try:
            with open(checksum_path_path, 'r') as checksum_file:
                checksum_path_content = checksum_file.read()
                checksum_file.close()
        except IOError:
            return "checksum is not present"

        image = Image(self.dir_getter.source_db_file_path())

        return "checksum passed in equality operation" if checksum_path_content == image.perform(
        ) else "checksum failed in equality operation"
Example #7
0
 def img_list(cls, user_name, album_id):
     album = Album.select().get(album_id)
     assert album is not None
     imgs = []
     if album.is_public or album.user_name == user_name:
         imgs = Image.select().filter(Image.album_id == album_id).order_by(Image.id.desc()).all()
     layout = []
     img_data = []
     row_height = [0] * 4
     for index, img in enumerate(imgs):
         img_data.append(img.get_json())
         row_num = math.floor(index / 4)
         col_num = index % 4
         log.info(f'{row_num}, {col_num}')
         layout.append({
             'x': 6 * (index % 4),
             'y': sum([lo.get('h', 0) if (i % 6) == col_num else 0 for i, lo in enumerate(layout)]),
             'w': 6,
             'h': math.floor(img.height / img.width * 9),
             'i': img.key,
             'index': index
         })
     for i in range(4):
         row_height[i] = sum([lo.get('h', 0) if index % 4 == i else 0 for index, lo in enumerate(layout)])
     return {
         'imgs': img_data,
         'layout': layout,
         'row_height': max(row_height)
     }
    def test_calculate_gradient_equals_zero_rectangle_area(self):
        pixels = (np.random.rand(150 * 150) < 0.5).astype(np.int16)
        pixels = pixels.reshape(150, 150)
        for x in range(0, 150):
            for y in range(0, 150):
                pixels[x][y] = 0
        pixels[0][0] = 0
        pixels[0][1] = 0
        pixels[0][2] = 0

        pixels[1][0] = 0
        pixels[1][1] = 0
        pixels[1][2] = 0

        pixels[2][0] = 0
        pixels[2][1] = 0
        pixels[2][2] = 0

        png.from_array(pixels, 'L').save("../Dane/rectangle__foo.png")
        myImage = Image("../Dane/rectangle__foo.png", 0)
        position = Position(1, 1)
        size = Size(10, 10)
        rArea = RectangleArea(myImage, position.x, position.y, size.height,
                              size.width)
        histogram = rArea.create_histogram()

        self.assertAlmostEqual(histogram.get(0), 0.0, delta=0.01)
        self.assertAlmostEqual(histogram.get(1), 0.0, delta=0.01)
        os.remove("../Dane/rectangle__foo.png")
Example #9
0
def getComic(comicId, lang="en"):
    from model.comic import Comic
    from model.image import Image

    c = get_db()

    t = text("SELECT title, DATE_FORMAT(pub_date, '%a, %d %b %Y %T') as pub_date_rss, explanation, type FROM comic WHERE comic_id = :comicId AND lang = :lang")
    results = c.execute(t, comicId = comicId, lang = lang)

    if results is None:
        return None

    title, pubDate, explanation, comicType = ("", "", "", "")

    for row in results:
        title = row['title']
        pubDate = row['pub_date_rss']
        if (row['explanation']):
            explanation = Markup(markdown.markdown(row['explanation']))
        else:
            explanation = ""
        comicType = row['type']


    t = text('SELECT filename, image_id, alt_text FROM image WHERE comic_id = :comicId AND lang = :lang')
    results = c.execute(t, comicId = comicId, lang = lang)
    images = []
    for row in results:
        newImage = Image(s.STATIC_URL + row['filename'], comicId, row['image_id'], row['alt_text'])
        images.append(newImage)

    return Comic(title, images, comicId, pubDate, explanation, comicType)
Example #10
0
def vote():
    """
    正负反馈api
    :return:
    00000-反馈成功
    10001-图片不存在
    10002-已经反馈过了
    10003-意料之外的参数类型
    """
    data = request.get_json()
    img_id = data.get('img_id')
    client_ip = request.headers.get("real_ip")
    if client_ip is None:
        client_ip = request.remote_addr
    vote_type = data.get('type')
    image = Image.objects(img_id=img_id).first()
    if not image:
        return json.dumps(dict(code=10001, ))
    if vote_type is 1:
        # 我觉得汪
        if client_ip in image.w_list:
            return json.dumps(dict(code=10002, ))
        image.update(push__w_list=client_ip, w=image.w + 1)
    elif vote_type is 0:
        # 我觉得喵
        if client_ip in image.m_list:
            return json.dumps(dict(code=10002, ))
        image.update(push__m_list=client_ip, m=image.m + 1)
    else:
        return json.dumps(dict(code=10003))

    return json.dumps(dict(code=0))
Example #11
0
def post_image():
    data = request.get_json()
    author = data.get('author')
    if author in ["", None]:
        author = 'Anonymous'
    image = Image(
        img_id=Count.get_number(Image),
        author=author,
        board=data.get('board', 'other'),
        word=data.get('word', ''),
        url=data.get('url').split(";"),
        visible=False,
    )
    image.save()
    r = dict(code=0)
    return json.dumps(r)
Example #12
0
def get_image():
    query_set = dict(visible=True, )
    if request.args.get('board') in ("cat", "dog", "other"):
        query_set['board'] = request.args.get('board')

    try:
        page = int(request.args.get('page'))
    except ValueError as e:
        page = 1
    paginate = Image.objects(**query_set).exclude(
        'w_list',
        'm_list',
    ).paginate(page=page, per_page=15)
    ms = paginate.items
    p = 0
    while paginate.has_next and p < 3:
        p += 1
        paginate = paginate.next()

    data = [m.api_data() for m in ms]
    return json.dumps(dict(
        code=0,
        data=data,
        page=page,
        next=p,
    ))
    def test_calculate_gradient_with_same_difference_circle_area(self):
        pixels = (np.random.rand(150 * 150) < 0.5).astype(np.int16)
        pixels = pixels.reshape(150, 150)

        for x in range(0, 150):
            for y in range(0, 150):
                pixels[x][y] = 0

        pixels[0][0] = 0
        pixels[0][1] = 100
        pixels[0][2] = 0

        pixels[1][0] = 150
        pixels[1][1] = 0
        pixels[1][2] = 250

        pixels[2][0] = 0
        pixels[2][1] = 200
        pixels[2][2] = 0

        png.from_array(pixels, 'L').save("../Dane/circle__foo.png")
        myImage = Image("../Dane/circle__foo.png", 0)
        position = Position(50, 50)
        radius = 50
        cArea = CircleArea(myImage, position.x, position.y, radius)
        histogram = cArea.create_histogram()
        for x in range(0, 8):
            if histogram.get(x) != 0:
                print(str(x) + ": " + str(histogram.get(x)))

        self.assertAlmostEqual(histogram.get(5), 0.0, delta=0.05)
        self.assertAlmostEqual(histogram.get(6), 0.0, delta=0.05)
        os.remove("../Dane/circle__foo.png")
Example #14
0
    def _process(self):
        wt = WaitProcess  #para manipular el diálogo de espera
        ui = self._dialog.ui
        pt = self._pixel_mapper[str(
            ui.pixelType.currentText())]  #tipo de pixel formato ITK
        dim = 3  #dimensión (siempre es 3D en este cargador)
        fileName = unicode(ui.fileName.text())  #nombre del fichero
        is_raw = ui.rawImage.isChecked()  #para saber si la imagen es raw
        width = ui.widthValue.value()  #anchoa de la imagen, si raw
        height = ui.heightValue.value()  #alato de la imagen, si raw
        depth = ui.depthValue.value(
        )  #profundidad de la imagen, si raw y si 3D

        wt.change_info("Inicializando el cargador")

        ImageType = itk.Image[pt, dim]  #tipo ITK de la imagen
        reader = itk.ImageFileReader[ImageType].New()  #creamos el reader
        rawIO = None  #imageIO para una imgen raw

        wt.change_value(10)
        if is_raw:
            wt.change_info("Inicializando el cargador RAW")
            rawIO = itk.RawImageIO[pt, dim].New()  #crear el rawIO
            rawIO.SetFileDimensionality(dim)  #poenrle dimensión 3D
            rawIO.SetDimensions(0, width)  #ancho
            rawIO.SetDimensions(1, height)  #alto
            rawIO.Setdimensions(2, depth)  #profundidad
            reader.SetImageIO(rawIO.GetPointer(
            ))  #especificar al Reader que el ImageIO que debe usar es RawIO
        wt.change_info("Cargando imagen")
        wt.change_value(20)
        reader.SetFileName(fileName)  #especificar el nombre del fichero a leer
        reader.Update()  #cargar la imagen
        wt.change_value(90)
        wt.change_info("Preparando la salida")

        uCharImageType = itk.Image[itk.UC, dim]
        toCharPixel = itk.RescaleIntensityImageFilter[ImageType,
                                                      uCharImageType].New()
        toCharPixel.SetOutputMaximum(255)
        toCharPixel.SetOutputMinimum(0)
        toCharPixel.SetInput(reader.GetOutput())
        toCharPixel.Update()

        name = fileName.split("/")[-1]  #obtener el nombre
        format = ""
        if name.rfind(".") != -1:
            format = name[name.rfind("."):]  #obtner el formato
            name = name[:name.rfind(
                ".")]  #quitarle al nombre lo que está después del punto
        #Crear la imagen que se va a devolver
        self._img = Image(itk.UC,
                          dim,
                          displayName=name,
                          originalFile=fileName,
                          originalFormat=format.upper())
        self._img.InternalImage = toCharPixel.GetOutput(
        )  #para la imagen a devolver esta es la imagen interna de ITK
        wt.stop()
Example #15
0
 def reload(self):
     if self.dst_image is None:
         self.dst_image = Image()
     self.dst_image.__init__(self.src_image.magic_word,
                             self.src_image.width,
                             self.src_image.height,
                             self.src_image.maxV,
                             self.src_image.pixel)
Example #16
0
 def delete_image(cls, user_name, id):
     image = Image.select().get(id)
     delete_status = QiniuService.delete_file(
         config.QI_NIU.get('img_bucket_name'), image.key)
     if not delete_status:
         raise ServerException('删除图片失败')
     image.delete()
     return True
Example #17
0
File: api.py Project: niczy/hyo
 def post(self):
   restaurant_name = self.request.get(NAME)
   restaurant_uid = self.request.get(RESTAURANT_UID)
   restaurant_image_data = self.request.get(IMAGE_DATA)
   image = Image.from_image_data(restaurant_image_data) 
   image.put()
   restaurant = restaurant_logic.add(restaurant_uid, restaurant_name, image.key)
   self.send_response(restaurant)
Example #18
0
def getComics(comicId=None,
              lang="en",
              orderBy="date",
              table="comic",
              imageTable="image"):
    from model.comic import Comic
    from model.image import Image

    c = get_db()

    langClause = " WHERE lang = :lang "

    idClause = ""
    if comicId is not None:
        idClause = "AND comic_id = :comicId "

    orderClause = ""
    if orderBy == "date":
        orderClause = "ORDER BY pub_date "
    elif orderBy == "popularity":
        orderClause = "ORDER BY popularity DESC"

    t = text(
        "SELECT comic_id, title, DATE_FORMAT(pub_date, '%a, %d %b %Y %T') as pub_date_rss, explanation, type FROM "
        + table + " WHERE status = 'active' AND lang = :lang " + idClause +
        orderClause)
    results = c.execute(t, comicId=comicId, lang=lang)

    if results is None:
        return None

    title, pubDate, explanation, comicType = ("", "", "", "")

    comics = []
    for row in results:
        title = row['title']
        pubDate = row['pub_date_rss']
        comicIdRow = None
        if (row['explanation']):
            explanation = Markup(markdown.markdown(row['explanation']))
        else:
            explanation = ""
        comicType = row['type']
        comicIdRow = row['comic_id']

        t = text('SELECT filename, image_id, alt_text, external_link FROM ' +
                 imageTable + ' WHERE comic_id = :comicId AND lang = :lang')
        results = c.execute(t, comicId=comicId, lang=lang)
        images = []
        for row in results:
            newImage = Image(s.STATIC_URL + row['filename'], comicId,
                             row['image_id'], row['alt_text'],
                             row['external_link'])
            images.append(newImage)

        comics.append(
            Comic(title, images, comicIdRow, pubDate, explanation, comicType))
    return comics
Example #19
0
 def delete_album(cls, id):
     album = Album.select().get(id)
     assert album is not None
     images = Image.select().filter(Image.album_id == id).all()
     for image in images:
         QiniuService.delete_file(config.QI_NIU.get('img_bucket_name'), image.key)
         image.delete()
     album.delete()
     return True
Example #20
0
 def __init__(self, pt, dim, to_pt=None):
     self._input_pixel_type = pt
     if to_pt is None:
         to_pt = pt
     self._output_pixel_type = to_pt
     self._dimension = dim
     self._input_image_type = itk.Image[pt, dim]
     self._output_image_type = itk.Image[to_pt, dim]
     self._internal_filter = None
     self._output_image = Image(self._output_pixel_type, self._dimension)
Example #21
0
 def from_db_object(self, db_object: Dict[str, Any]) -> Item:
     return Item(
         name=db_object['name'],
         price=db_object['price'],
         category=db_object['category'],
         shop=str(db_object['shop']),
         details=ProductDetails.from_db_object(db_object['details']),
         image=None if db_object['image'] is None else Image.from_db_object(
             db_object['image']),
         id=str(db_object['_id']))
Example #22
0
def get_comment():
    img_id = request.args.get("img_id")
    image = Image.objects(img_id=img_id).first()
    if not image:
        return json.dumps(dict(code=10001))
    data = [c.api_data() for c in image.comments]
    return json.dumps(dict(
        code=0,
        data=data,
    ))
    def setUp(self):
        image = Image("test_file.txt", "./tests/test_file.txt")

        replica_manager = SecondaryBackup(replica_manager_id=1, image=image)

        secondaries = {}
        secondaries[replica_manager.replica_manager_id] = replica_manager

        primary_backup = PrimaryBackup(replica_manager_id=0, image=image, secondaries=secondaries)

        self.action = primary_backup._check_all_secondary_health()
 def list_image(self):
     result = []
     list_image_url = 'http://%s:9292/v2/images' % self.registered_info[
         'cloud_ip']
     response = requests.get(list_image_url, headers=headers)
     images = json.loads(response.content.decode())['images']
     for image in images:
         # TODO 操作系统类型和版本
         new_image = Image(image['id'], image['name'], None, 'centos',
                           '7.4')
         result.append(new_image)
     return result
Example #25
0
def create_thumbnails():
    count = 0
    last_update = datetime.datetime.now()

    print "Creating thumbnails..."
    for image in Image.select():
        image.create_thumbnail(False)
        count += 1
        if (datetime.datetime.now() - last_update).total_seconds() > 5:
            last_update = datetime.datetime.now()
            print str(count) + " thumbnais created..."
    print "All thumnails created."
Example #26
0
 def add_item(self, name: str, price: float, category: str, shop: str,
              description: str, attributes: Dict[str, Any], image_id: str,
              image_url: str, session_id: str) -> str:
     item = Item(name=name,
                 price=price,
                 category=category,
                 shop=shop,
                 details=ProductDetails(description, attributes),
                 image=Image(image_id, image_url))
     self.validate(item, session_id)
     id = self.dao.store_one(item.to_db_object())
     return id
Example #27
0
File: api.py Project: niczy/hyo
 def post(self):
   restaurant_uid = self.request.get(RESTAURANT_UID)
   category_name = self.request.get(CATEGORY_NAME)
   dish_name = self.request.get(NAME)
   dish_image_data = self.request.get(IMAGE_DATA)
   img_key = None
   if dish_image_data:
     image = Image.from_image_data(dish_image_data) 
     image.put()
     img_key = image.key
   dish = dish_logic.add(restaurant_uid, category_name, dish_name, img_key)
   self.send_response(dish)
def apft_classification_of_whole_dataset(base_directory, classes, classifiers):
    for c in range(classes):
        for directory in os.listdir(base_directory):
            if os.path.isdir(os.path.join(base_directory, directory)):
                for filename in os.listdir(
                        os.path.join(base_directory, directory, str(c))):
                    path = os.path.join(base_directory, directory, str(c),
                                        filename)
                    image = Image(path, c)
                    result = apft_classification(classifiers, image,
                                                 classifiers)
                    print(str(path) + ', ' + str(c) + ', ' + str(result))
Example #29
0
    def img_upload(self, device_mac, device_pos, created_at, meta):
        if device_mac == "":
            return False

        if device_pos == "":
            return False
        dev = Device()
        pos = Position_Image()
        #print "upload_img",device_mac,device_pos

        device_id = dev.get_device_by_mac(device_mac)
        position_id = pos.get_position_id(device_id, device_pos)
        print "upload", device_id, position_id
        upload_path = os.path.join(get_pwd_dir(), CAPTURED_DIR)
        filename = meta['filename']
        filename = os.path.basename(filename)
        print filename, '----', upload_path

        filepath = os.path.join(upload_path, filename)
        with open(filepath, 'wb') as up:
            up.write(meta['body'])

        img = Image()
        img.path = filename
        img.position_id = position_id
        img.created_at = created_at
        img_id = img.create()
        r = redis.Redis()
        r.set('image_path_%s_%s' % (device_mac, device_pos), img.path)
        print img_id
        if not img_id:
            return False
        return True
def generate_classificator(parameters_config, negative_class_train_dir_path, positive_class_train_dir_path):
	#random.seed(11)
	global train_set
	train_set = []

	for filename in os.listdir(negative_class_train_dir_path):
		train_set.append(Image(os.path.join(negative_class_train_dir_path, filename), 0))
	for filename in os.listdir(positive_class_train_dir_path):
		train_set.append(Image(os.path.join(positive_class_train_dir_path, filename), 1))

	logger.debug('Loaded {} images from {} class training dataset'.format(len(os.listdir(negative_class_train_dir_path)), negative_class_train_dir_path))
	logger.debug('Loaded {} images from {} class training dataset'.format(len(os.listdir(positive_class_train_dir_path)), positive_class_train_dir_path))

	toolbox.register("evaluate", eval_classification)

	if parameters_config.getboolean("multithread"):
		pool = multiprocessing.Pool(parameters_config.getint("pool_size"))
		toolbox.register("map", pool.map)

	stats = tools.Statistics(lambda individual: individual.fitness.values)
	stats.register("avg", np.mean)
	stats.register("std", np.std)
	stats.register("min", np.min)
	stats.register("max", np.max)
	stats.register("learn_rate", learn_rate)

	pop = toolbox.population(n=parameters_config.getint("population"))
	crossover = parameters_config.getfloat("crossover")
	mutation = parameters_config.getfloat("mutation")
	epochs = parameters_config.getint("epochs")
	hof = tools.HallOfFame(1)
	algorithms.eaSimple(pop, toolbox, crossover, mutation, epochs, stats, halloffame=hof, verbose=False)

	toolbox.unregister("evaluate")

	if parameters_config.getboolean("multithread"):
		toolbox.register("map", map)
		pool.close()

	return pop, stats, hof
Example #31
0
def to_dict(event):
    image_query = Image.select().where(Image.event == event).order_by(
        Image.time)
    images = [image.id for image in image_query]

    return {
        "id": event.id,
        "summary": event.summary,
        "time": event.get_time().timestamp() * 1000,
        "tags": event.get_tags(),
        "url": event.get_value("url"),
        "images": images
    }
Example #32
0
 def getById(self, id):
     self.connect()
     image = None
     try:
         query = "SELECT * FROM Image WHERE id = {0}".format(id)
         self.cursor.execute(query)
         row = self.cursor.fetchone()
         if row is not None:
             image = Image(row=row)
     except Error as err:
         print(err)
     self.disconnect()
     return image
Example #33
0
 def getByMd5(self, md5):
     self.connect()
     image = None
     try:
         query = "SELECT * FROM Image WHERE md5 = \'{0}\'".format(md5)
         self.cursor.execute(query)
         row = self.cursor.fetchone()
         if row is not None:
             image = Image(row=row)
     except Error as err:
         print(err)
     self.disconnect()
     return image
def get_summery_info(user):
    dev_observed = Device_Observed()
    res = {'user_name': user.name, 'device_counts': dev_observed.count_user_devices(user.id), 'device_info': []}
    devices = dev_observed.observed_devices(user.id)
    print devices
    pos = Position()
    for dev in devices:
        contents_dev = {}
        print dev
        contents_dev['location'] = dev.location
        contents_dev['position_contents'] = []
        positions = pos.get_position_by_device_id(dev.id)
        if positions:
            for pos in positions:
                img = Image()
                image_count = img.count_by('where position_id = ?', pos.id)
                contents_dev['position_contents'].append({'position': pos.position,
                                                          'duration': pos.duration,
                                                          'image_count': image_count,
                                                          'object_name': pos.object_name})
        res['device_info'].append(contents_dev)

    return res
Example #35
0
def add(summary,
        time,
        tags=[],
        kvps={},
        hash=None,
        latitude=None,
        longitude=None,
        images=[]):
    result = Event(summary=summary,
                   time=time,
                   latitude=latitude,
                   longitude=longitude,
                   hash=hash)
    result.save()
    for tag in tags:
        result.add_tag(tag)
    for key in kvps.keys():
        db_key = Key.get_key(key)
        kvp = KeyValuePair(key=db_key, value=kvps[key], event=result)
        kvp.save(force_insert=True)
    for image_path in images:
        image = Image(event=result, file=image_path)
        image.save()
Example #36
0
    def __init__(self, app):
        self.src_image = Image()
        self.dst_image = None

        self.frame = Frame()
        self.panel = Panel(self.frame)

        #self.panel.open.Bind(wx.EVT_BUTTON, self.OnOpen)
        self.panel.choice.Bind(wx.EVT_CHOICE, self.onChoice)
        self.panel.go.Bind(wx.EVT_BUTTON, self.onGo)
        self.panel.mdf_param.Bind(wx.EVT_BUTTON, self.onModify)

        pub.subscribe(self.displayLeft, "LEFT IMAGE LOADED")
        pub.subscribe(self.displayRight, "RIGHT IMAGE CHANGED")

        ''' Load left image '''
        self.loadLeft(self.dir + self.src)

        ''' Load Reference image '''
        self.loadRef(self.dir + self.ref)

        self.frame.Show(True)
Example #37
0
 def testInsertEntity(self):
   image = Image.from_image_data(self.image_data)
   image.put()
   self.assertEqual('image/png', image.mimetype)
   self.assertEqual(1, len(image.query().fetch(2)))
Example #38
0
 def testDecode(self):
   decoded_data = Image.decode_image_data(self.base64_data)
   f = open('image.png', 'r')
   self.assertEqual(f.read(), decoded_data)
Example #39
0
    def get(self, *args,**kwargs):
        usr = self.get_current_user()
        device_observed = Device_Observed()
        position = Position_Image()
        image = Image()
        devices = device_observed.observed_devices(usr.id)
        if not devices or len(devices) < 1:
            return self.render('no_devices.html', user_name=usr.name, page_name="browser")

        positions = []
        for dev in devices:
            positions.extend(position.get_position_by_device_id(dev.id))
        current_position_id = self.get_argument('position_id', '')
        current_page = self.get_argument('page', '')
        if current_page:
            current_page = int(current_page)
        else:
            current_page = 1
            
        if current_position_id:
            current_position_id = current_position_id
        else:
            # positions = position.get_position_by_device_id(devices[0].id)
            if positions:
                current_position_id = positions[0].id
            else:
                current_position_id = 0
        total_image_num = image.count_by_position_id(current_position_id)
        total_page_num = total_image_num/IMAGE_NUMBER_FOR_PAGE+1
        start_image_num = (current_page - 1)*IMAGE_NUMBER_FOR_PAGE + 1

        if total_page_num < current_page:
            current_page = total_page_num

        images = image.find_by('order by id desc limit ? offset ?',
                               IMAGE_NUMBER_FOR_PAGE,
                               (current_page - 1)*IMAGE_NUMBER_FOR_PAGE)
        for img in images:
            img.created_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(img.created_at))
        # get the start and end page num
        if current_page > 3:
            start_page_num = current_page-3
        else:
            start_page_num = 1

        end_page_num = start_page_num+6
        if end_page_num>total_page_num:
            end_page_num = total_page_num
            start_page_num = end_page_num-6
            if start_page_num<1:
                start_page_num = 1

        end_image_num  = start_image_num+len(images)-1

        return self.render('browser.html',
                           page_name='browser',
                           positions=positions,
                           current_position_id=current_position_id,
                           current_page=current_page,
                           total_page_num=total_page_num,
                           total_image_num=total_image_num,
                           start_image_num=start_image_num,
                           end_image_num=end_image_num,
                           start_page_num=start_page_num,
                           end_page_num=end_page_num,
                           user_name=usr.name,
                           images=images
                           )
Example #40
0
class Controller:
    dir = 'C:\Users\Xing\git\CS555\image\\'
    #src = 'src_ascii.pgm'
    #src = 'moon_ascii.pgm'
    #src = 'Fig0507_a__ckt_board_orig__tif_ascii.pgm'
    #src = 'Fig0507_b__ckt_board_gauss_var_400__tif_ascii.pgm'
    #src = 'Fig0508_a__circuit_board_pepper_prob_pt1__tif_ascii.pgm'
    #src = 'Fig0508_b__circuit_board_salt_prob_pt1__tif_ascii.pgm'
    #src = 'Fig0510_a__ckt_board_saltpep_prob_pt05__tif_ascii.pgm'
    #src = 'Fig0512_a__ckt_uniform_var_800__tif_ascii.pgm'
    src = 'Fig0512_b__ckt_uniform_plus_saltpepr_prob_pt1__tif_ascii.pgm'
    #src = 'Fig0513_a__ckt_gaussian_var_1000_mean_0__tif_ascii.pgm'
    dst = 'dst.pgm'
    tmp = 'tmp.pgm'
    tmp2 = 'tmp2.pgm'
    ref = 'ref.pgm'
    #default = 'default.pgm'

    choice = None

    opt_01_width        = enum.DEFAULT_WIDTH_MIN
    opt_01_height       = enum.DEFAULT_HEIGHT_MIN

    opt_02_width        = enum.DEFAULT_WIDTH_MIN
    opt_02_height       = enum.DEFAULT_HEIGHT_MIN
    opt_02_selection    = enum.ZOOM_BILINEAR

    opt_03_gray_lvl     = enum.DEFAULT_GRAY_LEVEL
    opt_03_sgn          = enum.DEFAULT_SIGN

    opt_04_selection    = enum.DEFAULT_TRANS
    opt_04_c            = enum.DEFAULT_C
    opt_04_gamma        = enum.DEFAULT_GAMMA

    opt_05_selection    = enum.DEFAULT_HIST_EQ
    opt_05_resolution   = enum.DEFAULT_RESLTN_MIN

    opt_07_resolution   = enum.DEFAULT_RESLTN_MIN
    opt_07_selection    = enum.SP_FLT_SMOOTH
    opt_07_laplacian    = enum.DEFAULT_LAPLACIAN
    opt_07_k            = enum.DEFAULT_K

    opt_08_bits         = 64

    opt_09_resolution   = enum.DEFAULT_RESLTN_MIN
    opt_09_selection    = enum.RESTORE_ARITHMETIC

    def __init__(self, app):
        self.src_image = Image()
        self.dst_image = None

        self.frame = Frame()
        self.panel = Panel(self.frame)

        #self.panel.open.Bind(wx.EVT_BUTTON, self.OnOpen)
        self.panel.choice.Bind(wx.EVT_CHOICE, self.onChoice)
        self.panel.go.Bind(wx.EVT_BUTTON, self.onGo)
        self.panel.mdf_param.Bind(wx.EVT_BUTTON, self.onModify)

        pub.subscribe(self.displayLeft, "LEFT IMAGE LOADED")
        pub.subscribe(self.displayRight, "RIGHT IMAGE CHANGED")

        ''' Load left image '''
        self.loadLeft(self.dir + self.src)

        ''' Load Reference image '''
        self.loadRef(self.dir + self.ref)

        self.frame.Show(True)

    def onChoice(self, event):
        self.choice = event.GetString()
        print("choose: %s" % self.choice)

    def onGo(self, event):
        if self.choice == enum.OPT_01_SHRINK:
            print enum.OPT_01_SHRINK
            self.shrinkRight(self.dir + self.dst)
        elif self.choice == enum.OPT_02_ZOOM_BACK:
            print enum.OPT_02_ZOOM_BACK
            self.zoomBackRight(self.dir + self.dst)
        elif self.choice == enum.OPT_03_REDUCE_GL:
            print enum.OPT_03_REDUCE_GL
            self.reduceGrayLevel(self.dir + self.dst)
        elif self.choice == enum.OPT_04_TRANSFORM:
            print enum.OPT_04_TRANSFORM
            self.transform(self.dir + self.dst)
        elif self.choice == enum.OPT_05_HISTO_EQ:
            print enum.OPT_05_HISTO_EQ
            self.histogramEQ(self.dir + self.dst)
        elif self.choice == enum.OPT_06_HISTO_MAT:
            print enum.OPT_06_HISTO_MAT
            self.histogramMatch(self.dir + self.dst)
        elif self.choice == enum.OPT_07_SPATIAL_FLT:
            print enum.OPT_07_SPATIAL_FLT
            self.spatialFilterRight(self.dir + self.dst)
        elif self.choice == enum.OPT_08_BIT_PLANE:
            print enum.OPT_08_BIT_PLANE
            self.bitPlaneRight(self.dir + self.dst)
        elif self.choice == enum.OPT_09_RESTORE:
            print enum.OPT_09_RESTORE
            self.restoreImage(self.dir + self.dst)
        else:
            print "Do nothing"

    def onModify(self, event):
        if self.choice is not None:
            useMetal = False
            if 'wxMac' in wx.PlatformInfo:
                useMetal = self.cb.IsChecked()

            dlg = MdfDialog(self.panel, -1, self.choice, size=(350, 200),
                            style=wx.DEFAULT_DIALOG_STYLE,
                            useMetal=useMetal)
            dlg.CenterOnScreen()

            val = dlg.ShowModal()
            if val == wx.ID_OK:
                if self.choice == enum.OPT_01_SHRINK:
                    self.opt_01_width   = int(dlg.opt_01_text1.GetValue())
                    self.opt_01_height  = int(dlg.opt_01_text2.GetValue())
                elif self.choice == enum.OPT_02_ZOOM_BACK:
                    self.opt_02_width   = int(dlg.opt_02_text1.GetValue())
                    self.opt_02_height  = int(dlg.opt_02_text2.GetValue())
                    if dlg.opt_02_choice1.GetValue() is True:
                        self.opt_02_selection = enum.ZOOM_REPLIC
                    elif dlg.opt_02_choice2.GetValue() is True:
                        self.opt_02_selection = enum.ZOOM_NEAR_NGHR
                    elif dlg.opt_02_choice3.GetValue() is True:
                        self.opt_02_selection = enum.ZOOM_BILINEAR
                    print self.opt_02_selection
                elif self.choice == enum.OPT_03_REDUCE_GL:
                    self.opt_03_gray_lvl = int(dlg.opt_03_text1.GetValue())
                    if self.opt_03_gray_lvl < 1:
                        self.opt_03_gray_lvl = 1
                    elif self.opt_03_gray_lvl > 8:
                        self.opt_03_gray_lvl = 8
                    if dlg.opt_03_choice1.GetValue() is True:
                        self.opt_03_sgn = enum.REDUCE_GL_LEAST
                    elif dlg.opt_03_choice2.GetValue() is True:
                        self.opt_03_sgn = enum.REDUCE_GL_MOST
                    print("%s %d" % (self.opt_03_sgn, self.opt_03_gray_lvl))
                elif self.choice == enum.OPT_04_TRANSFORM:
                    if dlg.opt_04_choice1.GetValue() is True:
                        self.opt_04_selection = enum.TRANS_LOG
                        self.opt_04_c = float(dlg.opt_04_text1.GetValue())
                        print("%s %d %d" % (self.opt_04_selection,
                                        self.opt_04_c,
                                        self.opt_04_gamma))
                    elif dlg.opt_04_choice2.GetValue() is True:
                        self.opt_04_selection = enum.TRANS_POW
                        self.opt_04_c = float(dlg.opt_04_text2.GetValue())
                        self.opt_04_gamma = float(dlg.opt_04_text3.GetValue())
                        print("%s %d %d" % (self.opt_04_selection,
                                        self.opt_04_c,
                                        self.opt_04_gamma))
                elif self.choice == enum.OPT_05_HISTO_EQ:
                    if dlg.opt_05_choice1.GetValue() is True:
                        self.opt_05_selection = enum.HIST_EQ_GLOBAL
                    elif dlg.opt_05_choice2.GetValue() is True:
                        self.opt_05_selection = enum.HIST_EQ_LOCAL
                        self.opt_05_resolution = int(dlg.opt_05_text1.GetValue())
                elif self.choice == enum.OPT_07_SPATIAL_FLT:
                    if dlg.opt_07_choice1.GetValue() is True:
                        self.opt_07_resolution = int(dlg.opt_07_text1.GetValue())
                        self.opt_07_selection = enum.SP_FLT_SMOOTH
                    elif dlg.opt_07_choice2.GetValue() is True:
                        self.opt_07_resolution = int(dlg.opt_07_text1.GetValue())
                        self.opt_07_selection = enum.SP_FLT_MEDIAN
                    elif dlg.opt_07_choice3.GetValue() is True:
                        self.opt_07_laplacian = int(dlg.opt_07_text2.GetValue())
                        self.opt_07_selection = enum.SP_FLT_LAPLACIAN
                    elif dlg.opt_07_choice4.GetValue() is True:
                        self.opt_07_k = int(dlg.opt_07_text3.GetValue())
                        self.opt_07_selection = enum.SP_FLT_H_BOOST
                    print self.opt_07_selection
                elif self.choice == enum.OPT_08_BIT_PLANE:
                    self.opt_08_bits = 0
                    if dlg.opt_08_check1.GetValue() is True:
                        self.opt_08_bits |= 1
                    if dlg.opt_08_check2.GetValue() is True:
                        self.opt_08_bits |= 1 << 1
                    if dlg.opt_08_check3.GetValue() is True:
                        self.opt_08_bits |= 1 << 2
                    if dlg.opt_08_check4.GetValue() is True:
                        self.opt_08_bits |= 1 << 3
                    if dlg.opt_08_check5.GetValue() is True:
                        self.opt_08_bits |= 1 << 4
                    if dlg.opt_08_check6.GetValue() is True:
                        self.opt_08_bits |= 1 << 5
                    if dlg.opt_08_check7.GetValue() is True:
                        self.opt_08_bits |= 1 << 6
                    if dlg.opt_08_check8.GetValue() is True:
                        self.opt_08_bits |= 1 << 7
                    print self.opt_08_bits
                elif self.choice == enum.OPT_09_RESTORE:
                    self.opt_09_resolution = int(dlg.opt_09_text1.GetValue())
                    if dlg.opt_09_choice1.GetValue() is True:
                        self.opt_09_selection = enum.RESTORE_ARITHMETIC
                    elif dlg.opt_09_choice2.GetValue() is True:
                        self.opt_09_selection = enum.RESTORE_GEOMETRIC
                    elif dlg.opt_09_choice3.GetValue() is True:
                        self.opt_09_selection = enum.RESTORE_HARMONIC
                    elif dlg.opt_09_choice4.GetValue() is True:
                        self.opt_09_selection = enum.RESTORE_CONTRAHARM
                    elif dlg.opt_09_choice5.GetValue() is True:
                        self.opt_09_selection = enum.RESTORE_MAX
                    elif dlg.opt_09_choice6.GetValue() is True:
                        self.opt_09_selection = enum.RESTORE_MIN
                    elif dlg.opt_09_choice7.GetValue() is True:
                        self.opt_09_selection = enum.RESTORE_MIDPOINT
                    elif dlg.opt_09_choice8.GetValue() is True:
                        self.opt_09_selection = enum.RESTORE_ALPHA_TRIM
                    print self.opt_09_selection
            else:
                print "Cancelled..."

            dlg.Destroy()
        else:
            print "Not exist"


    def loadLeft(self, path):
        self.src_image.readContent(path)
        self.src_image.loadLeft(self.src_image,
                                enum.DEFAULT_WIDTH,
                                enum.DEFAULT_HEIGHT,
                                self.dir + self.tmp)

    def loadRef(self, path):
        self.opt_06_ref_image = Image()
        self.opt_06_ref_image.readContent(path)

    def reload(self):
        if self.dst_image is None:
            self.dst_image = Image()
        self.dst_image.__init__(self.src_image.magic_word,
                                self.src_image.width,
                                self.src_image.height,
                                self.src_image.maxV,
                                self.src_image.pixel)

    def shrinkRight(self, path):
        self.reload(self.src_image, self.dst_image)
        self.dst_image.shrinkRight(self.dst_image,
                                   self.opt_01_width,
                                   self.opt_01_height,
                                   path)

    def zoomBackRight(self, path):
        self.reload(self.src_image, self.dst_image)
        self.dst_image.zoomBack(self.dst_image,
                                self.opt_02_selection,
                                self.opt_02_width,
                                self.opt_02_height,
                                self.dir + self.tmp2,
                                enum.DEFAULT_WIDTH,
                                enum.DEFAULT_HEIGHT,
                                path)

    def reduceGrayLevel(self, path):
        self.reload()
        self.dst_image.reduceGrayLevel(self.dst_image,
                                       self.opt_03_gray_lvl,
                                       self.opt_03_sgn,
                                       path)

    def transform(self, path):
        self.reload()
        self.dst_image.transform(self.src_image,
                                 self.opt_04_selection,
                                 self.opt_04_c,
                                 self.opt_04_gamma,
                                 path)

    def histogramEQ(self, path):
        self.reload()
        self.dst_image.histogramEQ(self.src_image,
                                   self.opt_05_selection,
                                   self.opt_05_resolution,
                                   path)

    def histogramMatch(self, path):
        self.reload()
        self.dst_image.histogramMatch(self.src_image,
                                      self.opt_06_ref_image,
                                      path)

    def spatialFilterRight(self, path):
        self.reload()
        self.dst_image.spatialFilter(self.dst_image,
                                     self.opt_07_selection,
                                     self.opt_07_resolution,
                                     self.opt_07_laplacian,
                                     self.opt_07_k,
                                     path)

    def bitPlaneRight(self, path):
        self.reload()
        self.dst_image.bitPlane(self.dst_image,
                                self.opt_08_bits,
                                path)

    def restoreImage(self, path):
        self.reload()
        self.dst_image.restoreImage(self.dst_image,
                                    self.opt_09_selection,
                                    self.opt_09_resolution,
                                    path)

    def displayLeft(self, message):
        self.panel.setLeftImage(message.data)

    def displayRight(self, message):
        self.panel.setRightImage(message.data)
Example #41
0
 def loadRef(self, path):
     self.opt_06_ref_image = Image()
     self.opt_06_ref_image.readContent(path)