Exemplo n.º 1
0
    def __init__(self, data_directory):
        super(DatasetFromFolder, self).__init__()
        self.input_img_path = join(data_directory, 'input_img')
        self.gt_img_path = join(data_directory, 'gt_img')

        self.input_img_filenames = [x for x in listdir(self.input_img_path) if is_image_file(x)]
        self.input_img_filenames.sort()
        self.gt_img_filenames = [x for x in listdir(self.gt_img_path) if is_image_file(x)]
        self.gt_img_filenames.sort()

        transform_list = [transforms.ToTensor(),]

        self.transform = transforms.Compose(transform_list)
Exemplo n.º 2
0
	def default(self):
		"""
		Default action fetches all the stats and renders a template using them
		"""
		stats = {}

		# get all the thumbnails
		stats["Database stats"] = [
			("Number of marked files", Photo.get_num_marked_photos(), "raw"),
			("Number of DB files", Photo.get_count_by_date(), "raw")
		]

		stats["File System stats"] = []
		for s in [Photo.SMALL_THUMB_SIZE, Photo.MEDIUM_THUMB_SIZE]:
			stats["File System stats"].extend(self._thumb_info(s))
			
		num_images = 0
		total_size = 0
		for root, dirs, files in os.walk(S.BASE_FS_PATH):
			for f in files:
				if util.is_image_file(f):
					num_images += 1
					total_size += os.path.getsize(os.path.join(root, f))
		stats["File System stats"].extend([
			("Number of source images", num_images, "raw"),
			("Disk space", total_size, "bytes")
		])

		return self.construct_response(Template.render("stats.html", {"stats": stats}))
 def __init__(self, image_dir):
     super(DatasetFromFolder, self).__init__()
     self.a_path = join(image_dir, "a")
     self.b_path = join(image_dir, "b")
     self.image_filenames = [
         x for x in listdir(self.a_path) if is_image_file(x)
     ]
Exemplo n.º 4
0
def add_image_sequence(zip_file_path, video_name):
    # unzip the file to the extract path
    zip_ref = zipfile.ZipFile(zip_file_path)
    info_list = zip_ref.infolist()
    # create folder in upload
    timestamp = str(long(time.time()))
    upload_folder = config.UPLOAD_PATH + timestamp + '/'
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)
    path_list = []
    for info in info_list:
        file_name = info.filename
        _, file_extension = os.path.splitext(file_name)
        if util.is_image_file(file_name):
            file_path = zip_ref.extract(info, path=upload_folder)
            path_list.append(file_path)

    # now, all image paths are stored in the path_list
    # then extract these images
    extract_path = config.EXTRACT_PATH + os.path.splitext(
        basename(zip_file_path))[0]
    logger.debug('extract sequence begin %s' % extract_path)
    if not os.path.exists(extract_path):
        os.makedirs(extract_path)
    turkic_replacement.extract_image_sequences(path_list, extract_path)
    logger.debug('extract video end %s' % extract_path)
    # delete the temporary unzip path
    shutil.rmtree(upload_folder)
    # there is no label by default
    turkic_replacement.load(video_name, extract_path, [], zip_file_path,
                            current_user.id)
Exemplo n.º 5
0
    def default(self):
        """
		Default action fetches all the stats and renders a template using them
		"""
        stats = {}

        # get all the thumbnails
        stats["Database stats"] = [
            ("Number of marked files", Photo.get_num_marked_photos(), "raw"),
            ("Number of DB files", Photo.get_count_by_date(), "raw")
        ]

        stats["File System stats"] = []
        for s in [Photo.SMALL_THUMB_SIZE, Photo.MEDIUM_THUMB_SIZE]:
            stats["File System stats"].extend(self._thumb_info(s))

        num_images = 0
        total_size = 0
        for root, dirs, files in os.walk(S.BASE_FS_PATH):
            for f in files:
                if util.is_image_file(f):
                    num_images += 1
                    total_size += os.path.getsize(os.path.join(root, f))
        stats["File System stats"].extend([
            ("Number of source images", num_images, "raw"),
            ("Disk space", total_size, "bytes")
        ])

        return self.construct_response(
            Template.render("stats.html", {"stats": stats}))
Exemplo n.º 6
0
    def __init__(self, image_dir, mode, xy_size, img_size, norm, rotated=0, val=False):
        super(DatasetFromFolder, self).__init__()
        if 'no'==norm.partition('-')[2]:
            self.b ="b"
        else:
            self.b ="b_uniform"
        if mode=="AtoB":
            self.photo_path = join(image_dir, "a")
            self.sketch_path = join(image_dir, self.b)
        else:
            self.photo_path = join(image_dir, self.b)
            self.sketch_path = join(image_dir, "a")
        self.image_filenames = [x for x in listdir(self.photo_path) if is_image_file(x)]
        self.img_size = img_size
        self.val = val
        self.rgb = False if xy_size > 0 else True	#Training
        self.rotated=rotated
        self.norm = norm.partition('-')[0] if norm!='' else 'linear'

        #self.location_map = make_grid(1, img.size[0], img.size[1], norm=norm) as parameter in place of norm, so one time calculated& oft used
   
        # mean and std for Cityscapes
        CITYSCAPES_MEAN = [0.28689554, 0.32513303, 0.28389177]
        CITYSCAPES_STD = [0.18696375, 0.19017339, 0.18720214]

        transform_list = [transforms.ToTensor(),
                          transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]

        self.transform = transforms.Compose(transform_list)
 def __init__(self, image_dir, tranform=None):
     super(DataSetFromFolder, self).__init__()
     self.image_dir = image_dir
     self.image_filenames = [
         x for x in listdir(image_dir) if is_image_file(x)
     ]
     if transform:
         self.transform = transform
Exemplo n.º 8
0
    def preview(self):
        """
		Presents a preview of the files to be imported, giving the user an
		opportunity to view and change dates for images, highlighting images
		which may already be in the system, and the like.
		"""
        rel_import_dir = os.path.relpath(
            self._env.get("PATH_INFO", "").lstrip("/"), "import/preview")
        import_dir = os.path.realpath(
            os.path.join(S.IMPORT_DIR, rel_import_dir))
        file_listing = []
        import_identifier = hashlib.sha1()
        hashes = []
        session_file_struct = {}
        for base_dir, _, files in os.walk(import_dir):
            for f in files:
                if not util.is_image_file(f):
                    continue
                fc = util.FileContainer(os.path.join(import_dir, f),
                                        S.IMPORT_DIR)
                ts = util.get_time(fc, allow_date_from_path=False)
                if ts["time"] != None:
                    fc.time = time.strftime("%Y-%m-%d %H:%M:%S", ts["time"])
                hashes.append(fc.hash)
                import_identifier.update(fc.hash)
                file_listing.append(fc)
                session_file_struct[fc.hash] = {
                    "file_data": fc.__dict__(),
                    "conflicts": None
                }
            break
        file_listing = sorted(file_listing, key=itemgetter('name'))
        conflicts = Photo.get_by_hash(hashes)

        for conflict_hash in conflicts.keys():
            conflicts_for_json = [c.id for c in conflicts[conflict_hash]]
            session_file_struct[conflict_hash][
                "conflicts"] = conflicts_for_json
            session_file_struct[conflict_hash]["file_data"]["marked"] = True
            Logger.debug(session_file_struct)

        session_id = import_identifier.hexdigest()
        session_data = {
            "file_listing": session_file_struct,
            "rel_dir": rel_import_dir,
            "session_id": session_id
        }
        with open(os.path.join("/tmp", "%s.txt" % session_id), "w+") as f:
            f.write(json.dumps(session_data))

        return self.construct_response(
            Template.render(
                "import/preview.html", {
                    "files": file_listing,
                    "import_id": session_id,
                    "import_dir": rel_import_dir,
                    "conflicts": conflicts
                }), self._route_types.HTML_CONTENT_TYPE)
Exemplo n.º 9
0
	def preview(self):
		"""
		Presents a preview of the files to be imported, giving the user an
		opportunity to view and change dates for images, highlighting images
		which may already be in the system, and the like.
		"""
		rel_import_dir = os.path.relpath(self._env.get("PATH_INFO", "").lstrip("/"), "import/preview")
		import_dir = os.path.realpath(os.path.join(S.IMPORT_DIR, rel_import_dir))
		file_listing = []
		import_identifier = hashlib.sha1()
		hashes = []
		session_file_struct = {}
		for base_dir, _, files in os.walk(import_dir):
			for f in files:
				if not util.is_image_file(f):
					continue
				fc = util.FileContainer(os.path.join(import_dir, f), S.IMPORT_DIR)
				ts = util.get_time(fc, allow_date_from_path=False)
				if ts["time"] != None:
					fc.time = time.strftime("%Y-%m-%d %H:%M:%S", ts["time"])
				hashes.append(fc.hash)
				import_identifier.update(fc.hash)
				file_listing.append(fc)
				session_file_struct[fc.hash] = {
					"file_data": fc.__dict__(),
					"conflicts": None
				}
			break
		file_listing = sorted(file_listing, key=itemgetter('name'))
		conflicts = Photo.get_by_hash(hashes)

		for conflict_hash in conflicts.keys():
			conflicts_for_json = [c.id for c in conflicts[conflict_hash]]
			session_file_struct[conflict_hash]["conflicts"] = conflicts_for_json
			session_file_struct[conflict_hash]["file_data"]["marked"] = True
			Logger.debug(session_file_struct)

		session_id = import_identifier.hexdigest()
		session_data = {
			"file_listing": session_file_struct,
			"rel_dir": rel_import_dir,
			"session_id": session_id
		}
		with open(os.path.join("/tmp", "%s.txt" % session_id), "w+") as f:
			f.write(json.dumps(session_data))

		return self.construct_response(
			Template.render(
				"import/preview.html",
				{
					"files": file_listing,
					"import_id": session_id,
					"import_dir": rel_import_dir,
					"conflicts": conflicts
				}
			),
			self._route_types.HTML_CONTENT_TYPE
		)
Exemplo n.º 10
0
def get_all_image_details_in_dir(img_dir):
    file_names_list = os.listdir(img_dir)

    for file_name in file_names_list:
        # Only those files that are image files are considered.
        if (util.is_image_file(file_name)):
            file_full_path = os.path.join(img_dir, file_name)
            with Image.open(file_full_path) as img:
                yield (file_name, img.size)
Exemplo n.º 11
0
def get_matching_image_details(img_dir, keyword):
    file_names_list = os.listdir(img_dir)
    matching_file_names_list = util.get_matching_files(file_names_list,
                                                       keyword)

    for file_name in matching_file_names_list:
        if (util.is_image_file(file_name)):
            file_full_path = os.path.join(img_dir, file_name)
            with Image.open(file_full_path) as img:
                yield (file_name, img.size)
Exemplo n.º 12
0
    def __init__(self, image_dir):
        super(DatasetFromFolder, self).__init__()
        self.photo_path = join(image_dir, "a")
        self.sketch_path = join(image_dir, "b")
        self.image_filenames = [x for x in listdir(self.photo_path) if is_image_file(x)]

        transform_list = [transforms.ToTensor(),
                          transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]

        self.transform = transforms.Compose(transform_list)
Exemplo n.º 13
0
def classids():
    img_dir = "dataset/spherical/"
    cl_dir = "dataset/spherical2/"
    #np_img =np.zeros((512,3,1024))
    image_filenames = [x for x in os.listdir(img_dir) if is_image_file(x)]
    for image_name in image_filenames:
        np_img = load_img(img_dir + image_name, (1024, 512), rgb=True)
        image = encode_img_ids(np_img)
        #image = classify(np_img, img=False)
        save_img_np(decode_ids(image), cl_dir + image_name, (1024, 512))
Exemplo n.º 14
0
Arquivo: ldc.py Projeto: Surflyan/varc
def make_dataset(txt_file):
    image = []
    path_all = pd.read_table(txt_file, header=None, delim_whitespace=True)

    for i in range(len(path_all)):
        img_lr = path_all.iloc[i, 0]
        img_hr = path_all.iloc[i, 1]
        # img_sr = path_all.iloc[i, 2]

        if is_image_file(img_lr):
            item = (img_lr, img_hr)
            image.append(item)
    return image
Exemplo n.º 15
0
    def __init__(self, image_dir):
        super(DatasetFromFolder, self).__init__()
        self.input_path = join(image_dir, "input")
        self.output_path = join(image_dir, "output")
        self.image_filenames = [
            x for x in listdir(self.output_path) if is_image_file(x)
        ]

        # transform_list = [transforms.ToTensor(),
        #                   transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]

        transform_list = [transforms.ToTensor()]

        self.transform = transforms.Compose(transform_list)
Exemplo n.º 16
0
    def default(self):
        """
		Fetches a list of directories, files, or some combination thereof which
		need to be imported. The specific path is assumed from the PATH_INFO
		provided by self._env
		"""
        rel_import_dir = os.path.relpath(
            self._env.get("PATH_INFO", "").lstrip("/"), "import")
        dir_to_show = os.path.join(S.IMPORT_DIR, rel_import_dir)
        file_listing = []
        dir_listing = []
        get_details = True
        total_files = 0
        for base_dir, dirs, files in os.walk(dir_to_show):
            if get_details:
                for d in dirs:
                    dir_listing.append({
                        "rel_path":
                        os.path.relpath(os.path.join(base_dir, d),
                                        S.IMPORT_DIR),
                        "friendly_name":
                        d
                    })
                dir_listing = sorted(dir_listing,
                                     key=itemgetter("friendly_name"))
            for f in files:
                if not util.is_image_file(f):
                    continue
                total_files += 1
                if not get_details:
                    continue
                fc = util.FileContainer(os.path.join(base_dir, f), base_dir)
                time_resp = util.get_time(fc, allow_date_from_path=False)
                if time_resp["time"] != None:
                    fc.time = time.strftime(util.EXIF_DATE_FORMAT,
                                            time_resp["time"])
                file_listing.append(fc)
            get_details = False

        file_listing = sorted(file_listing, key=itemgetter('name'))

        return self.construct_response(
            Template.render(
                "import/listing.html", {
                    "dirs": dir_listing,
                    "files": file_listing,
                    "total_files": total_files,
                    "current_dir": rel_import_dir
                }), self._route_types.HTML_CONTENT_TYPE)
Exemplo n.º 17
0
    def __init__(self, image_dir):
        super(DatasetFromFolder, self).__init__()
        self.content_path = join(image_dir, "content")
        self.style_path = join(image_dir, "style")
        self.target_path = join(image_dir, "target")
        self.image_filenames = [
            x for x in listdir(self.target_path) if is_image_file(x)
        ]

        transform_list = [
            transforms.ToTensor(),
            transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
        ]

        self.transform = transforms.Compose(transform_list)
Exemplo n.º 18
0
    def __init__(self, image_dir, imageSize):
        super(DatasetFromFolder, self).__init__()
        self.photo_path = image_dir
        self.image_filenames = [
            x for x in listdir(self.photo_path) if is_image_file(x)
        ]

        transform_list = [
            transforms.Grayscale(num_output_channels=1),
            transforms.Resize(imageSize),
            transforms.ToTensor(),
            transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
        ]

        self.transform = transforms.Compose(transform_list)
Exemplo n.º 19
0
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and util.is_image_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('upload_file', filename=filename))
    return render_template('upload.html')
Exemplo n.º 20
0
	def default(self):
		"""
		Fetches a list of directories, files, or some combination thereof which
		need to be imported. The specific path is assumed from the PATH_INFO
		provided by self._env
		"""
		rel_import_dir = os.path.relpath(self._env.get("PATH_INFO", "").lstrip("/"), "import")
		dir_to_show = os.path.join(S.IMPORT_DIR, rel_import_dir)
		file_listing = []
		dir_listing = []
		get_details = True
		total_files = 0
		for base_dir, dirs, files in os.walk(dir_to_show):
			if get_details:
				for d in dirs:
					dir_listing.append({
						"rel_path": os.path.relpath(os.path.join(base_dir, d), S.IMPORT_DIR),
						"friendly_name": d
					})
				dir_listing = sorted(dir_listing, key=itemgetter("friendly_name"))
			for f in files:
				if not util.is_image_file(f):
					continue
				total_files += 1
				if not get_details:
					continue
				fc = util.FileContainer(os.path.join(base_dir, f), base_dir)
				time_resp = util.get_time(fc, allow_date_from_path=False)
				if time_resp["time"] != None:
					fc.time = time.strftime(util.EXIF_DATE_FORMAT, time_resp["time"])
				file_listing.append(fc)
			get_details = False

		file_listing = sorted(file_listing, key=itemgetter('name'))

		return self.construct_response(
			Template.render("import/listing.html", {
				"dirs": dir_listing,
				"files": file_listing,
				"total_files": total_files,
				"current_dir": rel_import_dir
			})
			, self._route_types.HTML_CONTENT_TYPE
		)
Exemplo n.º 21
0
    def __init__(self, image_dir, transform=None):
        super(DatasetFromFolder, self).__init__()

        if "flowers" in image_dir:
            self.image_dir = 'dataset/flowers/'
            with open("dataset/flowers/train/char-CNN-RNN-embeddings.pickle",
                      "rb") as f:
                self.embeddings = pickle.load(f, encoding='latin1')

            with open("dataset/flowers/train/filenames.pickle", "rb") as f:
                filenames = pickle.load(f, encoding='latin1')
                #filenames = [ (filename[:10] + '0' + filename[10:]) for filename in filenames]
                self.image_filenames = [
                    "{}.jpg".format(filename) for filename in filenames
                ]
        else:
            self.image_dir = image_dir
            self.image_filenames = [
                x for x in listdir(image_dir) if is_image_file(x)
            ]
        if transform:
            self.transform = transform
Exemplo n.º 22
0
# Testing settings
parser = argparse.ArgumentParser(description='pix2pix-PyTorch-implementation')
parser.add_argument('--dataset', required=True, help='facades')
parser.add_argument('--model',
                    type=str,
                    default='checkpoint/facades/netG_model_epoch_200.pth',
                    help='model file to use')
parser.add_argument('--cuda', action='store_true', help='use cuda')
opt = parser.parse_args()
print(opt)

netG = torch.load(opt.model)

#read the black and white image
image_dir = "dataset/{}/test/bw/".format(opt.dataset)
image_filenames = [x for x in os.listdir(image_dir) if is_image_file(x)]

transform_list = [
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
]

transform = transforms.Compose(transform_list)

for image_name in image_filenames:
    img = load_img(image_dir + image_name)
    img = transform(img)
    input = Variable(img, volatile=True).view(1, -1, 256, 256)

    if opt.cuda:
        netG = netG.cuda()
Exemplo n.º 23
0
 def __init__(self, image_dir):
     super(DatasetFromFolder, self).__init__()
     self.a_path = join(image_dir, "a")
     self.b_path = join(image_dir, "b")
     self.image_filenames = [x for x in listdir(self.a_path) if is_image_file(x)]
Exemplo n.º 24
0
def main(photo_file_dir):
    rotate_list = []
    box_list = []
    left_eye_list = []
    right_eye_list = []
    resize_scales = []
    target_files = []
    file_list = os.listdir(photo_file_dir)

    pd_size = 100

    for filename in file_list:
        if util.is_image_file(filename):
            photo_file = photo_file_dir + '/' + filename
            print photo_file
            response = util.face_detection(photo_file, True)

            detected = 0
            try:
                for faces in response['responses'][0]['faceAnnotations']:
                    detected = detected + 1
            except KeyError:
                continue
            except IndexError:
                continue

            if detected > 0:
                face = response['responses'][0]['faceAnnotations'][0]
                print 'rollAngle: %s' % face['rollAngle']
                print 'panAngle: %s' % face['panAngle']
                # if abs(face['panAngle']) > 30:
                #     continue
                print 'tiltAngle: %s' % face['tiltAngle']
                # if abs(face['tiltAngle']) > 30:
                #     continue
                print 'detectionConfidence: %s' % face['detectionConfidence']
                if face['detectionConfidence'] < 0.6:
                    continue

                landmarks = face['landmarks']
                for pos in landmarks:
                    x = pos['position']['x']
                    y = pos['position']['y']

                    if pos['type'] == 'LEFT_EYE_PUPIL':
                        left_eye_pos = (x, y)
                        left_eye_list.append(left_eye_pos)

                    if pos['type'] == 'RIGHT_EYE_PUPIL':
                        right_eye_pos = (x, y)
                        right_eye_list.append(right_eye_pos)

                # 瞳孔間距離の計算
                pupil_distance = math.sqrt(
                    (right_eye_pos[1] - left_eye_pos[1])**2 + (right_eye_pos[0] - left_eye_pos[0])**2)
                print 'pupilDistance: %s' % pupil_distance
                resize_scales.append(pd_size / pupil_distance)

                # 顔の領域を計算
                fdBoundingPoly = [(v['x'], v['y'])
                                  for v in face['fdBoundingPoly']['vertices']]
                expansion_rate = 1
                if util.use_google_face_detection():
                    expansion_rate = 1
                # 顔の領域を拡大 cloudvisionの場合はpupil_distance分拡大、dlibの場合もpupil_distance分拡大
                pd_int = int(round(pupil_distance * expansion_rate))
                im = cv2.imread(photo_file)
                (im_x, im_y) = im.shape[:2]
                startx = max(0, fdBoundingPoly[0][0] - pd_int)
                starty = max(0, fdBoundingPoly[0][1] - pd_int)
                end_x = min(im_x, fdBoundingPoly[2][0] + pd_int)
                end_y = min(im_y, fdBoundingPoly[2][1] + pd_int)
                box_list.append((startx, starty, end_x, end_y))

                # 右目を支点とした左目の位置の傾きを計算
                radian = math.atan2(
                    left_eye_pos[1] - right_eye_pos[1], right_eye_pos[0] - left_eye_pos[0])
                print 'rotate degree: %s' % math.degrees(radian)
                rotate_list.append(radian)

                target_files.append(photo_file)

            else:
                print "Face not found: %s" % photo_file

    # アフィン変換実行
    moved_left_eye = (200.0, 250.0)
    for (photo_file, left_eye, radian, resize) in zip(target_files, left_eye_list, rotate_list, resize_scales):
        dirname = os.path.dirname(photo_file)
        filename = os.path.basename(photo_file)
        if util.is_image_file(filename):
            root, ext = os.path.splitext(filename)
            affined_file = util.face_work_dir() + '/affined/' + root + '-affine' + ext

            cosr = np.cos(radian)
            sinr = np.sin(radian)
            rot = np.matrix((
                (cosr * resize, -sinr * resize),
                (sinr * resize,  cosr * resize)
            ))
            vec = np.array(left_eye)
            roteye = np.dot(rot, vec)
            move = (moved_left_eye[0] - roteye[0, 0],
                    moved_left_eye[1] - roteye[0, 1])

            matrix = [
                [cosr * resize, -sinr * resize, move[0]],
                [sinr * resize,  cosr * resize, move[1]]
            ]
            affine_matrix = np.float64(matrix)

            im = cv2.imread(photo_file)
            size = im.shape[:2]
            im_affine = cv2.warpAffine(
                im, affine_matrix, size, flags=cv2.INTER_LANCZOS4)
            crop_img = im_affine[0:512, 0:512]
            cv2.imwrite(affined_file, crop_img)
            symlink(affined_file, util.taken_date(photo_file))

    return 0
Exemplo n.º 25
0
 def __init__(self, image_dir):
     self.a_path = join(image_dir, "a")
     self.b_path = join(image_dir, "b")
     self.image_filenames = [
         x for x in listdir(self.a_path) if is_image_file(x)
     ]
Exemplo n.º 26
0
parser = argparse.ArgumentParser(description='pix2pix-PyTorch-implementation')
parser.add_argument('--dataset', required=True, help='cuhk')
parser.add_argument('--model', type=str, required=True, help='model file to use')
parser.add_argument('--input_nc', type=int, default=3, help='input image channels')
parser.add_argument('--output_nc', type=int, default=3, help='output image channels')
parser.add_argument('--ngf', type=int, default=64, help='generator filters in first conv layer')
parser.add_argument('--cuda', action='store_true', help='use cuda')
opt = parser.parse_args()
print(opt)
# opt.input_nc, opt.output_nc, opt.ngf
netG_state_dict = torch.load(opt.model)
netG = G(opt.input_nc, opt.output_nc, opt.ngf)
netG.load_state_dict(netG_state_dict)

image_dir = "dataset/{}/val_2018/".format(opt.dataset)
image_filenames = [x for x in os.listdir(image_dir) if is_image_file(x)]


batchsize=2
for image_name in image_filenames:
    img, shape = load_img(image_dir + image_name)
    
    input_x_np = np.zeros((batchsize, 3, 128, 128)).astype(np.float32)
   
    input_x_np[0,:] = np.asarray(img[0])
 
    input= Variable(torch.from_numpy(input_x_np))

    if opt.cuda:
        netG = netG.cuda()
        input = input.cuda()
Exemplo n.º 27
0
def dump_image_and_label_files(video_ids,
                               label_name_array,
                               remove_none_frame=False):
    if not os.path.exists(config.IMAGE_LIST_PATH):
        os.makedirs(config.IMAGE_LIST_PATH)
    if not os.path.exists(config.LABEL_LIST_PATH):
        os.makedirs(config.LABEL_LIST_PATH)
    if not os.path.exists(config.LABEL_NAME_PATH):
        os.makedirs(config.LABEL_NAME_PATH)

    print 'specified labels ' + str(label_name_array)
    timestamp = str(long(time.time()))
    image_file_path = config.IMAGE_LIST_PATH + timestamp + '.txt'
    label_file_path = config.LABEL_LIST_PATH + timestamp + '.txt'
    label_name_path = config.LABEL_NAME_PATH + timestamp + '.txt'

    session = db.session

    image_list_array = []
    label_list_array = []
    for video_id in video_ids:
        video, data = getdata(video_id)
        total_frames = video.totalframes
        extract_path = video.extract_path
        # for each video, we create a dict, to store all necessary labels
        # the key is the label name, the value is an array, since there might be multiple boxes for one label
        label_dict = {}
        for track in data:
            print 'get track with name %s, and length %s ' % (str(
                track.label), str(len(track.boxes)))
            if str(track.label) in label_name_array:
                if str(track.label) not in label_dict:
                    label_dict[str(track.label)] = []
                label_dict[str(track.label)].append(track.boxes)

        # after the traverse, w get all valid labels for that video
        iterators = []
        for label_name in label_name_array:
            if label_name in label_dict:
                iterators.append(label_dict[label_name])
            else:
                iterators.append([])
        # generate labels for each frame
        for frame in range(0, total_frames):
            img_path = Video.getframepath(frame, extract_path)
            if os.path.exists(img_path) and util.is_image_file(img_path):
                image_list_array.append(img_path)
                # traverse through the iterators, to check each label
                current_frame_labels = []
                # each iterator represent the pointer for the array of the class
                for i, iterator in enumerate(iterators):
                    label_boxes = []
                    for j, box_total in enumerate(iterator):
                        if frame >= len(box_total):
                            continue
                        box = box_total[frame]
                        # ignore these lost, occluded, generated labels
                        if box.lost or box.occluded:
                            continue
                        x1 = box.xtl
                        y1 = box.ytl
                        w = (box.xbr - box.xtl)
                        h = (box.ybr - box.ytl)
                        item = [str(x1), str(y1), str(w), str(h)]
                        label_boxes.append(item)
                    current_frame_labels.append(label_boxes)
                # generate the format for that frame of labels
                label_list_array.append(
                    generate_frame_label(current_frame_labels))

    if remove_none_frame:
        filled_image_list_array = []
        filled_label_list_array = []
        for i, frame_item in enumerate(label_list_array):
            # traverse through the frame, if there is no label exist, remove it
            if len(frame_item) >= len(label_name_array):
                # the length should be at least the length of a rect
                filled_image_list_array.append(image_list_array[i])
                filled_label_list_array.append(frame_item)
            else:
                print 'not labeled'
        print 'before remove none labeled array: length: %s, after %s' % (str(
            len(image_list_array)), str(len(filled_image_list_array)))
        image_list_array = filled_image_list_array
        label_list_array = filled_label_list_array

    total_frames = len(image_list_array)
    print 'total length of image %s, length of label %s, total frames %s' % (
        str(len(image_list_array)), str(
            len(label_list_array)), str(total_frames))
    util.write_list_to_file(image_list_array, image_file_path)
    util.write_list_to_file(label_list_array, label_file_path)

    # create the labels.txt file
    util.write_list_to_file(label_name_array, label_name_path)

    session.commit()
    return image_file_path, label_file_path, label_name_path
Exemplo n.º 28
0
                           anti_aliasing=True)
    # io.imshow(crop_resized)
    # io.show()
    im_comb = np.concatenate((im / 255., crop_resized), axis=0)
    return im_comb


if __name__ == '__main__':
    # Specify the folder of tested images
    folder = './result/ipiu/1/'
    # Specify the top-left and bottom-right corners of the interested area
    start = (141, 231)
    end = (275, 330)
    # start = (146, 124)
    # end = (272, 234)
    # start = (150, 0)
    # end = (200, 50)
    # start = (200, 240)
    # end = (240, 275)
    hr_list = [
        join(folder, x) for x in sorted(listdir(folder))
        if util.is_image_file(x)
    ]
    for fname in hr_list:
        im = io.imread(fname)
        # plt.imshow(im)
        # plt.show()
        im_expand = bbox_expand(im, start, end)
        name = os.path.basename(fname)
        io.imsave(join(folder, 'bbox_{}'.format(name)), im_expand)