Exemplo n.º 1
0
    def from_file(path, query, duration=None):
        media_type = guess_type(path)

        if media_type is MEDIA_TYPE_VIDEO:
            if duration is None: duration = get_video_duration(path)
            tmp = create_temporary_file(".snap.mp4")
            output_path = tmp.name
            subprocess.Popen(["ffmpeg", "-y", "-i", path, output_path]).wait()

        elif media_type is MEDIA_TYPE_IMAGE:
            image = Image.open(path)

            draw = ImageDraw.Draw(image)
            font = ImageFont.truetype("aller-font.ttf", 28)
            draw.text((10, 10),
                      'Name:' + query['title'] + ' Artist:' + query['artist'],
                      (255, 0, 0),
                      font=font)
            del draw

            tmp = create_temporary_file(".jpg")
            output_path = tmp.name
            resize_image(image, output_path)
            if not duration:
                duration = DEFAULT_DURATION

        else:
            raise UnknownMediaType(
                "Could not determine media type of the file")

        return Snap(path=output_path, media_type=media_type, duration=duration)
Exemplo n.º 2
0
    def Test_Data(self, path):
        for File in os.listdir(path):
            full_path = os.path.abspath(os.path.join(path, File))
            if os.path.isdir(full_path):
                self.Test_Data(full_path)
            else:
                if File.endswith('.png') or File.endswith('.PNG'):

                    #Find & Store images
                    image = cv2.cvtColor(resize_image(cv2.imread(full_path)),
                                         cv2.COLOR_BGR2RGB).astype(
                                             np.float32) / 255
                    if image.shape != (64, 64, 3):
                        print('detected image with incorrect size: ' +
                              full_path)
                        print('the shape of this image is:' + str(image.shape))
                        image = resize_image(image)
                    #image = cv2.imread(full_path)
                    self.test_image.append(image)

                    #Create Labels
                    #getting the upper level path
                    folder_path = os.path.abspath(
                        os.path.join((full_path), "../"))
                    upper_folder_path = os.path.abspath(
                        os.path.dirname(folder_path))
                    #do a string subtraction
                    current_label = Get_ID(folder_path, upper_folder_path)

                    for i in range(len(self.order_sheet)):
                        temp = int(current_label) - self.minimun_id
                        if temp == self.order_sheet[i]:
                            current_label = i
                    self.test_label = np.append(self.test_label, current_label)
Exemplo n.º 3
0
    def inference(self, input_image, output_dir, save_images=False):
        # Create scaled image
        scaled_image = resize_image(input_image, 2)

        # Create y and scaled y image
        input_y_image = convert_rgb_to_y(input_image)
        scaled_y_image = resize_image(input_y_image, self.scale)

        output_y_image = self.run(input_y_image, scaled_y_image)

        # Create result image
        scaled_ycbcr_image = convert_rgb_to_ycbcr(scaled_image)
        result_image = convert_y_and_cbcr_to_rgb(output_y_image,
                                                 scaled_ycbcr_image[:, :, 1:3])

        if save_images:
            save_image(input_image, "{}/original.jpg".format(output_dir))
            save_image(scaled_image, "{}/bicubic.jpg".format(output_dir))
            save_image(scaled_y_image,
                       "{}/bicubic_y.jpg".format(output_dir),
                       is_rgb=False)
            save_image(output_y_image,
                       "{}/result_y.jpg".format(output_dir),
                       is_rgb=False)
            save_image(result_image, "{}/result.jpg".format(output_dir))

        return result_image
Exemplo n.º 4
0
    def mold_inputs(self, images, tile_images):
        molded_images = []
        molded_tile_images = []
        windows = []
        for image in images:
            molded_image, window, scalse, padding = utils.resize_image(
                image,
                min_dim=self.config.IMAGE_MIN_DIM,
                max_dim=self.config.IMAGE_MAX_DIM,
                padding=self.config.IMAGE_PADDING)

            molded_image = mold_image(molded_image, self.config)
            molded_images.append(molded_image)
            windows.append(window)

        for tile_image in tile_images:
            tile_image, _, _, _ = utils.resize_image(
                tile_image,
                min_dim=0,
                max_dim=128,
                padding=self.config.IMAGE_PADDING
            )
            molded_tile_image = mold_image(tile_image, self.config)
            molded_tile_images.append(molded_tile_image)

        molded_images = np.stack(molded_images)
        molded_tile_images = np.stack(molded_tile_images)
        windows = np.stack(windows)

        return molded_images, molded_tile_images, windows
Exemplo n.º 5
0
    def update_avatar(self):

        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        imgsDir = os.path.join(os.getenv(__envKey__), 'avatar')
        fileName, _ = QFileDialog.getOpenFileName(self, "Your Avatar", imgsDir, "All Files (*);;Img Files (*.jpg)",
                                                  options=options)
        if fileName:
            baseFileName = self.username + '.avatar.jpg'
            desPth = os.path.join(imgsDir, baseFileName)

            if desPth == fileName:
                pass
            elif os.path.exists(desPth):
                if os.path.exists(desPth + '.showLayout_old'):
                    os.remove(desPth + '.showLayout_old')

                os.rename(desPth, desPth + '.showLayout_old')
                resize_image(fileName, desPth)
                shutil.copy2(fileName, desPth)
                image = QPixmap.fromImage(QImage(desPth))
                self.avatar.setPixmap(image)
                self.avatar.update()
                self.settings.setValue(self.username, desPth)
                self.updateAvatar.emit(True)
Exemplo n.º 6
0
    def __call__(self, img):
        """
    Args:
        img (numpy array): Image to be scaled.

    Returns:
        numpy array: Rescaled image
    """
        # sample interpolation method
        interpolation = random.sample(self.interpolations, 1)[0]

        # scale the image
        if isinstance(self.size, int):
            h, w = img.shape[0], img.shape[1]
            if (w <= h and w == self.size) or (h <= w and h == self.size):
                return img
            if w < h:
                ow = int(self.size)
                oh = int(round(self.size * h / w))
                img = resize_image(img, (ow, oh), interpolation=interpolation)
            else:
                oh = int(self.size)
                ow = int(round(self.size * w / h))
                img = resize_image(img, (ow, oh), interpolation=interpolation)
            return img
        else:
            #################################################################################
            # Solution
            #################################################################################
            img = resize_image(img, self.size, interpolation=interpolation)
            return img
  def __call__(self, img):
    """
    Args:
        img (numpy array): Image to be scaled.

    Returns:
        numpy array: Rescaled image
    """
    # sample interpolation method
    interpolation = random.sample(self.interpolations, 1)[0]

    # scale the image
    if isinstance(self.size, int):
      #################################################################################
      # Fill in the code here
      height, width, depth = img.shape
      if (width<height):
        img = resize_image(img,(self.size,round(self.size*height/width)), interpolation)
      else:
        img = resize_image(img,(round(self.size*width/height),self.size), interpolation)

      #################################################################################
      return img
    else:
      #################################################################################
      # Fill in the code here
      rows= self.size[0]
      cols= self.size[1]
      img = resize_image(img,(cols,rows), interpolation)
      #################################################################################
      return img
Exemplo n.º 8
0
    def __augment_images(self, image_batch):
        images = []
        for image in image_batch:
            npimage = np.array(image, dtype=np.uint8)

            if self.max_image_width == self.height:
                npimage = cv2.resize(npimage, (self.max_image_width, self.height))

            agimage = self.augmentor.seq.augment_images([npimage])[0]
            random_str = uuid.uuid4()

            agimage, _ = resize_image(agimage,
                self.max_image_width,
                self.height
            )

            # just for debug
            if self.test_augment_image:
                npimage, _ = resize_image(npimage,
                    self.max_image_width,
                    self.height
                )
                cv2.imwrite("augmentimages/" + str(random_str) + "_0bf.jpg", npimage)
                cv2.imwrite("augmentimages/" + str(random_str) + "_1ag.jpg", agimage)
            images.append(agimage)
        return images
Exemplo n.º 9
0
def add_user_avatar():
    data = request.get_json()
    if not data['user']:
        return jsonify({'user': {
            'errors': {
                'global': 'incorrect format'
            }
        }}), 400
    data = data['user']

    user = User.query.filter_by(username=data['userName']).first()
    if not user:
        return jsonify(
            {'user': {
                'errors': {
                    'global': 'Username doesn\'t exist'
                }
            }}), 400
    if not data['imageUrl']:
        return jsonify({'user': {
            'errors': {
                'global': 'incorrect image'
            }
        }}), 400

    imgdata = data['imageUrl'].split(',')[1]
    imgdata = base64.decodebytes(imgdata.encode())
    filename = 'avatars/{0}_avatar.jpg'.format(data['userName'])
    user.avatar = filename

    with open(filename, 'wb') as f:
        f.write(imgdata)
    resize_image(filename)
    user_image = username_to_base64_avatar(data['userName'])
    return jsonify({'user': {'avatar': data['imageUrl']}})
Exemplo n.º 10
0
def im_register_scale(im_fixed, im_moving, pad_size=None, options={}):
    """For registering only by re-scaling."""
    if pad_size is None:
        pad_size = (im_moving.shape[0] * 2, im_moving.shape[1] * 2)

    orig_size = (im_moving.shape[0], im_moving.shape[1])

    im_fixed = utils.resize_image(im_fixed, pad_size)
    im_moving = utils.resize_image(im_moving, pad_size) / 255

    im_f_shape = im_fixed.shape
    im_m_shape = im_moving.shape

    assert im_f_shape == im_m_shape

    # random initialization and assignment
    scale_init = 1.25
    error_function = lambda x: utils.ssd_scale(
        x, im_fixed, im_moving, pad_size, disp=options.get('disp', True))
    scale_optimized = scipy.optimize.minimize(error_function,
                                              scale_init,
                                              method='Nelder-Mead',
                                              options=options,
                                              jac=False)

    # apply solved registration
    im_registered = skimage.transform.rescale(im_moving,
                                              scale_optimized.x,
                                              multichannel=True,
                                              mode='constant',
                                              anti_aliasing=True)

    return utils.resize_image(im_registered, orig_size)
Exemplo n.º 11
0
    def __init__(self, **opts):
        self.uploaded = False
        self.duration = opts['duration']
        self.media_type = opts['media_type']

        if 'sender' in opts:
            self.sender = opts['sender']
            self.snap_id = opts['snap_id']
            self.from_me = False

        else:
            self.snap_id = uuid.uuid4().hex
            self.from_me = True

        if 'data' in opts:
            self.media_type = opts['media_type']

            suffix = "." + file_extension_for_type(opts['media_type'])

            self.file = create_temporary_file(suffix)

            if self.media_type is MEDIA_TYPE_VIDEO:
                self.file.write(opts['data'])
                self.file.flush()

            else:
                image = Image.open(StringIO(opts['data']))
                resize_image(image, self.file.name)

        else:
            path = opts['path']
            self.file = open(path)
Exemplo n.º 12
0
    def __call__(self, img):
        # sample interpolation method
        interpolation = random.sample(self.interpolations, 1)[0]

        for attempt in range(self.num_trials):

            # sample target area / aspect ratio from area range and ratio range
            area = img.shape[0] * img.shape[1]
            target_area = random.uniform(self.area_range[0],
                                         self.area_range[1]) * area
            aspect_ratio = random.uniform(self.ratio_range[0],
                                          self.ratio_range[1])

            #################################################################################
            # Solution
            #################################################################################
            # compute the width and height
            # note that there are two possibilities
            # crop the image and resize to output size
            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))
            if random.random() < 0.5:
                w, h = h, w

            # crop the image
            if w <= img.shape[1] and h <= img.shape[0]:
                x1 = random.randint(0, img.shape[1] - w)
                y1 = random.randint(0, img.shape[0] - h)

                img = img[y1:y1 + h, x1:x1 + w]
                if isinstance(self.size, int):
                    img = resize_image(img, (self.size, self.size),
                                       interpolation=interpolation)
                else:
                    img = resize_image(img,
                                       self.size,
                                       interpolation=interpolation)
                return img

        # Fall back
        if isinstance(self.size, int):
            im_scale = Scale(self.size, interpolations=self.interpolations)
            img = im_scale(img)
            #################################################################################
            # Solution
            #################################################################################
            # with a square sized output, the default is to crop the patch in the center
            # (after all trials fail)
            h, w = img.shape[0], img.shape[1]
            th, tw = self.size, self.size
            x1 = int(round((w - tw) / 2.))
            y1 = int(round((h - th) / 2.))
            img = img[y1:y1 + th, x1:x1 + tw]
            return img
        else:
            # with a pre-specified output size, the default crop is the image itself
            im_scale = Scale(self.size, interpolations=self.interpolations)
            img = im_scale(img)
            return img
Exemplo n.º 13
0
    def __call__(self, img):
        # sample interpolation method
        interpolation = random.sample(self.interpolations, 1)[0]
        for attempt in range(self.num_trials):

            area = img.shape[0] * img.shape[1]
            target_area = random.uniform(self.area_range[0],
                                         self.area_range[1]) * area
            aspect_ratio = random.uniform(self.ratio_range[0],
                                          self.ratio_range[1])

            h, w, c = img.shape
            #using the aspect ratio and the target area, we get 2 equations
            #assuming aspect is w/h
            h1 = int(math.sqrt(target_area / aspect_ratio))
            w1 = int(aspect_ratio * h1)

            #assuming the aspect ratio is h/w
            w2 = int(math.sqrt(target_area / aspect_ratio))
            h2 = int(w2 * aspect_ratio)
            #in order for the patch to be acceptable both the height and width have to be
            if (w1 <= w and h1 <= h):
                start_w = (w - w1) // 2
                start_h = (h - h1) // 2
                img = img[start_h:start_h + h1,
                          start_w:start_w + w1]  ## cropped image
                img = img * 255
                img = img.astype(np.uint8)
                img = resize_image(img, (self.size, self.size), interpolation)
                return img
            if (w2 <= w and h2 <= h):
                start_w = (w - w2) // 2
                start_h = (h - h2) // 2
                img = img[start_h:start_h + h2,
                          start_w:start_w + w2]  ## cropped image
                img = img * 255
                img = img.astype(np.uint8)
                img = resize_image(img, (self.size, self.size), interpolation)
                return img

        # Fall back
        if isinstance(self.size, int):
            im_scale = Scale(self.size, interpolations=self.interpolations)
            img = im_scale(img)
            start_w = (w - self.size) // 2
            start_h = (h - self.size) // 2
            img = img[start_h:start_h + self.size,
                      start_w:start_w + self.size]  ## cropped image
            # with a square sized output, the default is to crop the patch in the center
            # (after all trials fail)
            return img
        else:
            # with a pre-specified output size, the default crop is the image itself
            im_scale = Scale(self.size, interpolations=self.interpolations)
            img = im_scale(img)
            return img
Exemplo n.º 14
0
    def get_images(self, index):
        image = self.get_random_patched_image(self.files[index])

        if random.randrange(2) == 0:
            image = np.fliplr(image)

        input_image = resize_image(image, 1 / self.scale)
        input_scaled_image = resize_image(input_image, self.scale)

        return input_image, input_scaled_image, image
Exemplo n.º 15
0
    def evaluate(self, filepath):
        input_image = align_image(load_image(filepath), self.scale)
        input_y_image = resize_image(convert_rgb_to_y(input_image),
                                     1 / self.scale)
        input_scaled_y_image = resize_image(input_y_image, self.scale)

        output_y_image = self.run(input_y_image, input_scaled_y_image)
        ground_truth_y_image = convert_rgb_to_y(input_image)

        return calc_psnr_and_ssim(ground_truth_y_image,
                                  output_y_image,
                                  border=self.scale)
Exemplo n.º 16
0
    def update_ui(self, _initial_image, _new_image):
        initial_image = resize_image(_initial_image, (700, 700))
        new_image = resize_image(_new_image, (700, 700))

        self._initial_image = ImageTk.PhotoImage(initial_image,
                                                 master=self._root)
        self._modified_image = ImageTk.PhotoImage(new_image, master=self._root)

        self._label_initial_image['image'] = self._initial_image
        self._label_modified_image['image'] = self._modified_image

        self._label_initial_image['width'] = 0
        self._label_initial_image['height'] = 0
        self._label_modified_image['width'] = 0
        self._label_modified_image['height'] = 0
Exemplo n.º 17
0
	def get(self, uuid_no,page_id):
		upload_file = str(uuid_no)
		image_paths = []
		if upload_file.endswith('.pdf'):
			image_paths = convert_pdf(upload_file)
		else:
			image_paths.append(upload_file)

		resize_image(image_paths)
		if page_id == '0':
			response = requisiton_page(image_paths)
		if page_id == '1':
			response = info_page(image_paths)

		return (response)
Exemplo n.º 18
0
def neo_gen_gallery(sdir, fdest, tdest, source, absroot):
    index = """<div class="container"> <div class="gallery">"""
    print("SOURCE", source)
    print("SDIR", sdir)
    flist = os.listdir(source + sdir)
    for item in flist:
        print(item, "X")
        try:
            utils.resize_image(source + sdir + item, 1200,
                               absroot + tdest + item)
            index = index + """<a href='""" + fdest + item + """' target='_blank'><img src='""" + tdest + item + """'></a>"""
        except:
            pass
    index = index + "</div></div>"
    return (index)
Exemplo n.º 19
0
    def __load_data(self):
        """
            Load all the images in the folder
        """

        print('Loading data')

        examples = []

        count = 0
        skipped = 0
        for f in os.listdir(self.examples_path):
            if len(f.split('_')[0]) > self.max_char_count:
                continue
            arr, initial_len = resize_image(
                os.path.join(self.examples_path, f),
                self.max_image_width
            )
            examples.append(
                (
                    arr,
                    f.split('_')[0],
                    label_to_array(f.split('_')[0])
                )
            )
            count += 1

        return examples, len(examples)
Exemplo n.º 20
0
def generate_arrays_from_file(lines, batch_size):
    # 获取总长度
    n = len(lines)
    i = 0
    num = 0
    while 1:
        num += 1
        print("num++++++++++++++++++++++++++++++" + str(num))
        X_train = []
        Y_train = []
        # 获取一个batch_size大小的数据
        for b in range(batch_size):
            if i == 0:
                np.random.shuffle(lines)
            name = lines[i].split(';')[0]
            # 从文件中读取图像
            img = cv2.imread('./data/image/train' + '/' + name)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            img = img / 255
            X_train.append(img)
            Y_train.append(lines[i].split(';')[1])
            # 读完一个周期后重新开始
            i = (i + 1) % n
        # 处理图像
        X_train = utils.resize_image(X_train, (224, 224))
        X_train = X_train.reshape(-1, 224, 224, 3)
        Y_train = np_utils.to_categorical(np.array(Y_train), num_classes=2)
        yield (X_train, Y_train)
Exemplo n.º 21
0
def my_resize(image, config):
    image, window, scale, padding = utils.resize_image(
        image,
        min_dim=config.IMAGE_MIN_DIM,
        max_dim=config.IMAGE_MAX_DIM,
        padding=config.IMAGE_PADDING)
    return image, window, scale, padding
Exemplo n.º 22
0
    def __load_data(self):
        """
            Load all the images in the folder
        """

        print('Loading data')

        examples = []

        count = 0
        skipped = 0
        for i, f in enumerate(os.listdir(self.examples_path)):
            if i > 100000:
                break
            if len(f.split('_')[0]) > self.max_char_count:
                continue
            arr, initial_len = resize_image(
                os.path.join(self.examples_path, f),
                self.max_image_width
            )
            examples.append(
                (
                    arr,
                    f.split('_')[0].lower(),
                    label_to_array(f.split('_')[0].lower()),
                    label_to_array_2(f.split('_')[0].lower())
                )
            )
            count += 1

        print(count)

        return examples, len(examples)
Exemplo n.º 23
0
def home():
    if request.method == 'GET':
        return render_template('home.html')

    if request.method == 'POST':
        if 'image' not in request.files:
            flash('No file was uploaded.')
            return redirect(request.url)

        image_file = request.files['image']

        if image_file.filename == '':
            flash('No image was uploaded.')
            return redirect(request.url)

        if image_file and is_valid_file_type(image_file.filename):
            passed = False
            try:
                filename = generate_random_name(image_file.filename)
                filepath = os.path.join('/tmp/images/', filename)
                image_file.save(filepath)
                passed = resize_image(filepath)
            except Exception:
                passed = False

            if passed:
                return redirect(url_for('predict', filename=filename))
            else:
                flash('An error occurred, try again.')
                return redirect(request.url)
Exemplo n.º 24
0
def main():

    model = YOLOv3Net(cfgfile, model_size, num_classes)

    model.load_weights(weightfile)

    class_names = load_class_names(class_name)

    win_name = 'Yolov3 detection'
    cv2.namedWindow(win_name)

    #specify the vidoe input.
    # 0 means input from cam 0.
    # For vidio, just change the 0 to video path
    cap = cv2.VideoCapture(0)
    frame_size = (cap.get(cv2.CAP_PROP_FRAME_WIDTH),
                  cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    try:
        while True:
            start = time.time()
            ret, frame = cap.read()
            if not ret:
                break

            resized_frame = tf.expand_dims(frame, 0)
            resized_frame = resize_image(resized_frame,
                                         (model_size[0], model_size[1]))

            pred = model.predict(resized_frame)

            boxes, scores, classes, nums = output_boxes( \
                pred, model_size,
                max_output_size=max_output_size,
                max_output_size_per_class=max_output_size_per_class,
                iou_threshold=iou_threshold,
                confidence_threshold=confidence_threshold)

            img = draw_outputs(frame, boxes, scores, classes, nums,
                               class_names)
            cv2.imshow(win_name, img)

            stop = time.time()

            seconds = stop - start
            # print("Time taken : {0} seconds".format(seconds))

            # Calculate frames per second
            fps = 1 / seconds
            print("Estimated frames per second : {0}".format(fps))

            key = cv2.waitKey(1) & 0xFF

            if key == ord('q'):
                break

    finally:
        cv2.destroyAllWindows()
        cap.release()
        print('Detections have been performed successfully.')
Exemplo n.º 25
0
    def __iter__(self):
        examples = []
        for f in os.listdir(self.examples_path):
            label, _ = f.split('_')
            if len(f.split('_')[0]) > self.max_char_count:
                continue
            arr, _ = resize_image(os.path.join(self.examples_path, f),
                                  self.max_image_width)
            # to lower
            label_lower = label.lower()
            examples.append((arr, label_lower, label_to_array(label_lower)))

            if len(examples) == self.batch_size:
                raw_batch_x, raw_batch_y, raw_batch_la = zip(*examples)
                batch_y = np.reshape(np.array(raw_batch_y), (-1))

                batch_dt = sparse_tuple_from(np.array(raw_batch_la))

                raw_batch_x = np.swapaxes(raw_batch_x, 1, 2)

                batch_x = np.reshape(
                    np.array(raw_batch_x),
                    (len(raw_batch_x), self.max_image_width, 32, 1))
                yield (batch_y, batch_dt, batch_x)
                examples = []
Exemplo n.º 26
0
def generate_arrays_from_file(lines, batch_size):
    # 获取数据集的总长度
    n = len(lines)
    i = 0
    while 1:
        X_train = []
        Y_train = []
        # 获取一个batch_size大小的数据
        for b in range(batch_size):
            if i == 0:
                np.random.shuffle(lines)
            name = lines[i].split(';')[0]
            # 从文件中读取图像
            img = cv2.imread(r"E:\pyprogram\dataset\image\train/" + name)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            img = img / 255
            X_train.append(img)
            Y_train.append(lines[i].split(';')[1])
            # 读完一个周期后重新开始
            i = (i + 1) % n
        # 处理图像
        X_train = utils.resize_image(X_train, (224, 224))
        X_train = X_train.reshape(-1, 224, 224, 3)
        Y_train = np_utils.to_categorical(np.array(Y_train), num_classes=2)
        yield (X_train, Y_train) # yield相当于return不过下次进入循环从上次退出的地方开始循环,不是从头开始
Exemplo n.º 27
0
def get_icon(id, type_, size, callback):
    if size:
        skey = '%s:%s:%s' % (type_, id, size)
        data = icons[skey]
        if data:
            callback(bytes(data))
            return
    key = '%s:%s' % (type_, id)
    data = icons[key]
    if not data:
        type_ = 'preview' if type_ == 'cover' else 'cover'
        key = '%s:%s' % (type_, id)
    if size:
        skey = '%s:%s:%s' % (type_, id, size)
    if size:
        data = icons[skey]
        if data:
            size = None
    if not data:
        data = icons[key]
    if not data:
        data = icons.black()
        size = None
    if size:
        data = icons[skey] = resize_image(data, size=size)
    data = bytes(data) or ''
    callback(data)
Exemplo n.º 28
0
def video():
    config.batch_size = 1
    ig = tf.placeholder(shape=(1, config.Config['min_dim'], config.Config['min_dim'], 3), dtype=tf.float32)
    pred_loc, pred_confs, vbs = inception_500_dsl.inception_v2_ssd(ig, config)
    box, score, pp = predict(ig, pred_loc, pred_confs, vbs, config.Config)
    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        saver.restore(sess, '/home/dsl/all_check/face_detect/voc-aug/model.ckpt-91518')
        cap = cv2.VideoCapture('/media/dsl/20d6b919-92e1-4489-b2be-a092290668e4/face_detect/jijing.mp4')
        fourcc = cv2.VideoWriter_fourcc(*'MJPG')

        out = cv2.VideoWriter('output.mpg', fourcc, 20.0, (1920, 1080))
        #cap = cv2.VideoCapture(0)
        cap.set(3,320*3)
        cap.set(4,320*3)
        t1 = time.time()
        while True:
            ret ,frame = cap.read()
            if not ret:
                break
            if time.time() -t1 >240:
                break

            img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            org, window, scale, padding, crop = utils.resize_image(img, min_dim=config.Config['min_dim'], max_dim=config.Config['min_dim'])

            img = (org / 255.0 - 0.5) * 2
            img = np.expand_dims(img, axis=0)
            t = time.time()

            bx, sc, p = sess.run([box, score, pp], feed_dict={ig: img})

            fps = int(1/(time.time() - t)*10)/10.0

            cv2.putText(frame,  'fps:' + str(fps), (10, 30),
                        cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), lineType=cv2.LINE_AA)

            bxx = []
            cls = []
            scores = []
            for s in range(len(p)):
                if sc[s] > 0.4:
                    bxx.append(bx[s])
                    cls.append(p[s])
                    scores.append(sc[s])
            if len(bxx)>0:
                finbox = utils.revert_image(scale,padding,config.Config['min_dim'],np.asarray(bxx))
                for ix,s in enumerate(finbox):
                    cv2.rectangle(frame,pt1=(s[0],s[1]),pt2=(s[2],s[3]),color=(0,255,0),thickness=2)
                    cv2.putText(frame, config.VOC_CLASSES[cls[ix]]+'_'+str(scores[ix])[0:4], (s[0], s[1]), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), lineType=cv2.LINE_AA)
            out.write(frame)
            cv2.imshow('fram',frame)

            if cv2.waitKeyEx(1) & 0xFF == ord('q'):
                break
        print('ss')
        out.release()
        cap.release()
        cv2.destroyAllWindows()
Exemplo n.º 29
0
def detect():
    config.batch_size = 1
    ig = tf.placeholder(shape=(1, 512, 512, 3), dtype=tf.float32)
    pred_loc, pred_confs, vbs = inceptionv3_500_ince.inception_v2_ssd(ig,config)
    box,score,pp = predict(ig,pred_loc, pred_confs, vbs,config.Config)
    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        saver.restore(sess, '/home/dsl/all_check/face_detect/tx/model.ckpt-12318.data-00000-of-00001')
        for ip in glob.glob('/media/dsl/20d6b919-92e1-4489-b2be-a092290668e4/VOCdevkit/VOCdevkit/VOC2012/JPEGImages/*.jpg'):
            print(ip)
            img = cv2.imread(ip)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            org, window, scale, padding, crop = utils.resize_image(img, min_dim=512, max_dim=512)

            img = (org/ 255.0-0.5)*2
            img = np.expand_dims(img, axis=0)
            t = time.time()
            bx,sc,p= sess.run([box,score,pp],feed_dict={ig:img})
            print(time.time()-t)
            bxx = []
            cls = []
            scores = []
            for s in range(len(p)):
                if sc[s]>0.2:
                    bxx.append(bx[s])
                    cls.append(p[s])
                    scores.append(sc[s])
            if len(bxx) > 0:
                #visual.display_instances(org,np.asarray(bxx)*300)
                visual.display_instances_title(org,np.asarray(bxx)*512,class_ids=np.asarray(cls),class_names=config.VOC_CLASSES,scores=scores)
Exemplo n.º 30
0
def main():

    model = YOLOv3Net(cfgfile, model_size, num_classes)
    model.load_weights(weightfile)

    class_names = load_class_names(class_name)

    image = cv2.imread(img_path)
    image = np.array(image)
    image = tf.expand_dims(image, 0)

    resized_frame = resize_image(image, (model_size[0], model_size[1]))
    pred = model.predict(resized_frame)

    boxes, scores, classes, nums = output_boxes( \
        pred, model_size,
        max_output_size=max_output_size,
        max_output_size_per_class=max_output_size_per_class,
        iou_threshold=iou_threshold,
        confidence_threshold=confidence_threshold)

    image = np.squeeze(image)
    img = draw_outputs(image, boxes, scores, classes, nums, class_names)

    win_name = 'Image detection'
    cv2.imshow(win_name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Exemplo n.º 31
0
    def load_data(self):
        """Load all the images in the folder
        """

        print("Loading data")

        examples = []

        count = 0
        skipped = 0
        for f in os.listdir(self.examples_path):
            if len(f.split("_")[0]) > self.max_char_count:
                continue
            arr, initial_len = resize_image(
                imread(os.path.join(self.examples_path, f), mode="L"),
                self.max_image_width,
            )
            examples.append((
                arr,
                f.split("_")[0],
                label_to_array(f.split("_")[0], self.char_vector),
            ))
            count += 1

        return examples, len(examples)
Exemplo n.º 32
0
    def batch_generator(self, queue):
        """Takes a queue and enqueue batches in it
        """

        generator = GeneratorFromDict(language=self.language)
        while True:
            batch = []
            while len(batch) < self.batch_size:
                img, lbl = generator.next()
                batch.append((
                    resize_image(np.array(img.convert("L")),
                                 self.max_image_width)[0],
                    lbl,
                    label_to_array(lbl, self.char_vector),
                ))

            raw_batch_x, raw_batch_y, raw_batch_la = zip(*batch)

            batch_y = np.reshape(np.array(raw_batch_y), (-1))

            batch_dt = sparse_tuple_from(
                np.reshape(np.array(raw_batch_la), (-1)))

            raw_batch_x = np.swapaxes(raw_batch_x, 1, 2)

            batch_x = np.reshape(
                np.array(raw_batch_x),
                (len(raw_batch_x), self.max_image_width, 32, 1))
            if queue.qsize() < 20:
                queue.put((batch_y, batch_dt, batch_x))
            else:
                pass
Exemplo n.º 33
0
def get_icon_app(id, type_, size, callback):
    with db.session():
        from item.models import Item
        item = Item.get(id)
        if not item:
            data = ''
        else:
            if type_ == 'cover' and not item.meta.get('cover'):
                type_ = 'preview'
            if type_ == 'preview' and not item.files.count():
                type_ = 'cover'
            if size:
                skey = '%s:%s:%s' % (type_, id, size)
            key = '%s:%s' % (type_, id)
            data = None
            if size:
                data = icons[skey]
                if data:
                    size = None
            if not data:
                data = icons[key]
            if not data:
                data = icons.black()
                size = None
            if size:
                data = icons[skey] = resize_image(data, size=size)
            data = bytes(data) or ''
    callback(data)
Exemplo n.º 34
0
 def get_image (self, name):
     if not len(self.images) or name is None or name not in self.images:
         return None
     self.pb = load_image(name)
     if self.pb is not None:
         rv = resize_image(self.pb, self.width, self.height, method=self.method)
         self.filename = name
         return rv
     return None
Exemplo n.º 35
0
    def from_file(path, duration = None):
        media_type = guess_type(path)

        if media_type is MEDIA_TYPE_VIDEO:
            if duration is None: duration = get_video_duration(path)
            tmp = create_temporary_file(".snap.mp4")
            output_path = tmp.name
            subprocess.Popen(["ffmpeg", "-y", "-i", path, output_path]).wait()

        elif media_type is MEDIA_TYPE_IMAGE:
            image = Image.open(path)
            tmp = create_temporary_file(".jpg")
            output_path = tmp.name
            resize_image(image, output_path)
            if duration is None: duration = DEFAULT_DURATION

        else:
            raise Exception, "Could not determine media type of the file"

        return Snap(path = output_path, media_type = media_type, duration = duration)
Exemplo n.º 36
0
def _build_image_grid(input_images,
                      gt_projs,
                      pred_projs,
                      input_voxels,
                      output_voxels,
                      vis_size=128):
  """Builds a grid image by concatenating the input images."""
  quantity = input_images.shape[0]

  for row in xrange(int(quantity / 3)):
    for col in xrange(3):
      index = row * 3 + col
      input_img_ = utils.resize_image(input_images[index, :, :, :], vis_size,
                                      vis_size)
      gt_proj_ = utils.resize_image(gt_projs[index, :, :, :], vis_size,
                                    vis_size)
      pred_proj_ = utils.resize_image(pred_projs[index, :, :, :], vis_size,
                                      vis_size)
      gt_voxel_vis = utils.resize_image(
          utils.display_voxel(input_voxels[index, :, :, :, 0]), vis_size,
          vis_size)
      pred_voxel_vis = utils.resize_image(
          utils.display_voxel(output_voxels[index, :, :, :, 0]), vis_size,
          vis_size)
      if col == 0:
        tmp_ = np.concatenate(
            [input_img_, gt_proj_, pred_proj_, gt_voxel_vis, pred_voxel_vis], 1)
      else:
        tmp_ = np.concatenate([
            tmp_, input_img_, gt_proj_, pred_proj_, gt_voxel_vis, pred_voxel_vis
        ], 1)
    if row == 0:
      out_grid = tmp_
    else:
      out_grid = np.concatenate([out_grid, tmp_], 0)

  return out_grid
Exemplo n.º 37
0
    def __init__(self, **opts):
        self.uploaded = False
        self.duration = opts['duration']
        self.media_type = opts['media_type']

        if 'sender' in opts:
            self.sender = opts['sender']
            self.snap_id = opts['snap_id']
            self.from_me = False

        else:
            self.snap_id = uuid.uuid4().hex
            self.from_me = True

        if 'data' in opts:
            self.media_type = opts['media_type']

            suffix = "." + get_file_extension(opts['media_type'])

            self.file = create_temporary_file(suffix)

            if (self.media_type is MEDIA_TYPE_VIDEO) or (self.media_type is MEDIA_TYPE_VIDEO_NOAUDIO) or (opts['data'][0:2] == b'\x00\x00'):
                self.file.write(opts['data'])
                self.file.flush()

            else:
                print self.media_type#, opts
                try:
                    image = Image.open(StringIO(opts['data']))
                    resize_image(image, self.file.name)
                except Exception as e:
                    print "Unable to process image "+str(e)

        else:
            path = opts['path']
            self.file = open(path)
Exemplo n.º 38
0
def _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels):
  """Build the visualization grid with py_func."""
  quantity, img_height, img_width = input_images.shape[:3]
  for row in xrange(int(quantity / 3)):
    for col in xrange(3):
      index = row * 3 + col
      input_img_ = input_images[index, :, :, :]
      gt_proj_ = gt_projs[index, :, :, :]
      pred_proj_ = pred_projs[index, :, :, :]
      pred_voxel_ = utils.display_voxel(pred_voxels[index, :, :, :, 0])
      pred_voxel_ = utils.resize_image(pred_voxel_, img_height, img_width)
      if col == 0:
        tmp_ = np.concatenate([input_img_, gt_proj_, pred_proj_, pred_voxel_],
                              1)
      else:
        tmp_ = np.concatenate(
            [tmp_, input_img_, gt_proj_, pred_proj_, pred_voxel_], 1)
    if row == 0:
      out_grid = tmp_
    else:
      out_grid = np.concatenate([out_grid, tmp_], 0)

  out_grid = out_grid.astype(np.uint8)
  return out_grid
Exemplo n.º 39
0
 def load_pb (self, pb):
     self.category.pb = pb
     self.image.set_from_pixbuf(resize_image(pb, self.width, self.height, method=self.method))