Ejemplo n.º 1
0
def exif(img, vision):
    """
    writes the json data into the exif fields of the output jpg, which is
    currently called from detector.
    """

    metadata = pyexiv2.ImageMetadata(img)
    metadata.read()

    # info = metadata.exif_keys
    # for key in info:
    # print("key: " + str(key))

    metadata['Exif.Photo.UserComment'] = json.dumps(vision)
    metadata['Exif.Image.Make'] = 'python'
    try:
        metadata.write()
    except IOError:
        print('An error occured trying to read the file.')

    # printing the exif data to check it was all written
    metadata = pyexiv2.ImageMetadata(img)
    metadata.read()
    userdata = json.loads(metadata['Exif.Photo.UserComment'].value)
    pprint.pprint(userdata)
Ejemplo n.º 2
0
def get_create_time(fname, camera_manufacturer):
    if camera_manufacturer == 'DJI':
        metadata = pyexiv2.ImageMetadata(fname)
        metadata.read()
        create_time_local = metadata['Exif.Image.DateTime'].value
        create_time = (create_time_local - datetime(
            1970, 1, 1)).total_seconds() - 3600 * 9  # GMT+9 (S.Korea)
        return create_time
    elif camera_manufacturer == 'AIMIFY/FLIR/Visible':
        metadata = pyexiv2.ImageMetadata(fname)
        metadata.read()
        create_time_local = metadata['Exif.GPSInfo.GPSTimeStamp'].value
        create_time = (create_time_local - datetime(
            1970, 1, 1)).total_seconds() - 3600 * 9  # GMT+9 (S.Korea)
        return create_time

        # time_string = fname.split('/')[-1][0:15]
        # year = int(time_string[0:4])
        # month = int(time_string[4:6])
        # day = int(time_string[6:8])
        # hour = int(time_string[9:11])
        # minute = int(time_string[11:13])
        # second = int(time_string[13:15])
        #
        # dt = datetime(year, month, day, hour, minute, second)

        return datetime.timestamp(dt)
Ejemplo n.º 3
0
def main(file_list, outdir):
    # copy parameters to arrays
    K = np.array([[1743.23312, 0, 2071.06177], [0, 1741.57626, 1476.48298],
                  [0, 0, 1]])
    d = np.array([-0.307412748, 0.300929683, 0, 0,
                  0])  # just use first two terms (no translation)

    logging.debug("Starting loop")
    for image in file_list:
        logging.debug("var %s", image)
        imgname = image.split("/")[-1]
        new_image_path = os.path.join(outdir, imgname)
        if not os.path.exists(new_image_path):
            logging.debug("Undistorting %s . . . ", imgname)
            # read one of your images
            img = cv2.imread(image)
            h, w = img.shape[:2]

            # un-distort
            newcamera, roi = cv2.getOptimalNewCameraMatrix(K, d, (w, h), 0)
            newimg = cv2.undistort(img, K, d, None, newcamera)

            # cv2.imwrite("original.jpg", img)
            cv2.imwrite(new_image_path, newimg)

            # Write metadata
            old_meta = pyexiv2.ImageMetadata(image)
            new_meta = pyexiv2.ImageMetadata(new_image_path)
            old_meta.read()
            new_meta.read()
            old_meta.copy(new_meta)
            new_meta.write()
        else:
            logging.debug("Image already processed")
Ejemplo n.º 4
0
def shrinkIfNeededByPIL(path, maxDimension):
    if imageMaxDimensionByPIL(path) > maxDimension:
        print "Shrinking " + path
        imagePath = getTempPath(path)
        img = Image.open(path)
        (w, h) = img.size
        if (w > h):
            img2 = img.resize((maxDimension, (h * maxDimension) / w),
                              Image.ANTIALIAS)
        else:
            img2 = img.resize(((w * maxDimension) / h, maxDimension),
                              Image.ANTIALIAS)
        img2.save(imagePath, 'JPEG', quality=99)

        # now copy EXIF data from original to new
        src_image = pyexiv2.ImageMetadata(path)
        src_image.read()
        dst_image = pyexiv2.ImageMetadata(imagePath)
        dst_image.read()
        src_image.copy(dst_image, exif=True)
        # overwrite image size based on new image
        dst_image["Exif.Photo.PixelXDimension"] = img2.size[0]
        dst_image["Exif.Photo.PixelYDimension"] = img2.size[1]
        dst_image.write()

        return imagePath
    return path
Ejemplo n.º 5
0
 def save_with_compr(self, out_dir, compression):
     img = cv2.imread(self.path)
     shape = img.shape
     for blur in self.blurs:
         blur.apply(img, shape)
     outpath = os.path.join(out_dir, os.path.basename(self.path))
     metadata = pyexiv2.ImageMetadata(self.path)
     metadata.read()
     cv2.imwrite(outpath, img, [cv2.IMWRITE_JPEG_QUALITY, compression])
     metadata_new = pyexiv2.ImageMetadata(outpath)
     metadata_new.read()
     metadata.copy(metadata_new)
     for key in metadata.exif_keys:
         try:
             tag = metadata[key]
         except UnicodeDecodeError as err:
             sys.stderr.write("Skipping EXIF key {} due to {}\n".format(key, err))
             metadata_new.__delitem__(key)
     if "Exif.Image.Orientation" in metadata:
         metadata_new.__delitem__("Exif.Image.Orientation")
     # Update thumbnail
     thumb = pyexiv2.exif.ExifThumbnail(metadata_new)
     np_arr = numpy.frombuffer(bytes(thumb.data), numpy.uint8)
     if np_arr.size > 0:
         thumb_img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
         thumb_shape = thumb_img.shape
         for blur in self.blurs:
             blur_for_thumb = blur.transform_to(shape, thumb_shape)
             blur_for_thumb.apply(thumb_img, thumb_shape)
         retval, buf = cv2.imencode(".jpg", thumb_img)
         thumb.data = buf.tobytes()
     metadata_new.write()
     return os.path.getsize(outpath)
Ejemplo n.º 6
0
def do_copy(args):
    """ Copy relevant tags from one file to another
    """
    src_photo = args[0]
    dst_photo = args[1]

    try:
        metadata_src = pyexiv2.ImageMetadata(src_photo)
        metadata_src.read()
    except IOError:
        cprint('Error reading %s' % src_photo, 'red', 'on_yellow')
        exit(1)
    try:
        metadata_dst = pyexiv2.ImageMetadata(dst_photo)
        metadata_dst.read()
    except IOError:
        cprint('Error reading %s' % dst_photo, 'red', 'on_yellow')
        exit(1)

    print "Writing to %s" % dst_photo
    try:
        dtag = metadata_src[DATE_TAG]
        print 'DateTimeOriginal: %s' % str(dtag.value)
        metadata_dst[DATE_TAG] = str(dtag.value)
    except KeyError:
        pass
    try:
        ctag = metadata_src[COMMENT_TAG]
        print 'UserComment: %s' % str(ctag.value)
        metadata_dst[COMMENT_TAG] = str(ctag.value)
    except KeyError:
        pass
    metadata_dst.write()
Ejemplo n.º 7
0
def import_image(path):
    '''
	import a single image.

	'''
    # get the filename...
    file_name = os.path.split(path)[-1]
    file_name_base = file_name.split('.')[0]

    # start with metadata...
    metadata = pyexiv2.ImageMetadata(path)
    metadata.read()

    # add path to the original as a comment...
    if metadata['Exif.Photo.UserComment'].value.strip() == '':
        metadata['Exif.Photo.UserComment'] = 'RAW path: ' + os.path.abspath(
            path)
    else:
        metadata['Exif.Photo.UserComment'] = preview_metadata[
            'Exif.Photo.UserComment'].value + '\n\nRAW path: ' + os.path.abspath(
                path)

    # extract preview from raw file (largest)...
    orig_preview_path = os.path.join(ARCHIVE_PATH, HIRES_DIR, file_name)
    ##	orig_preview = metadata.previews[-1]
    ##	orig_preview.write_to_file(orig_preview_path)

    ##!!! HACK: use a lib instead of exec-ing a command for each image...
    cmd = 'exiv2 -f -l "%s" -ep%s "%s"' % (os.path.join(
        ARCHIVE_PATH, TMP_DIR), len(metadata.previews), path)
    os.system(cmd)
    ##!!! HACK: guessing the file name...
    orig_preview_path = os.path.join(
        ARCHIVE_PATH, TMP_DIR,
        '%s-preview%s.jpg' % (file_name_base, len(metadata.previews)))

    # generate preview and save to preview dir...
    preview_path = os.path.join(ARCHIVE_PATH, PREVIEW_DIR, file_name_base)
    orig = Image.open(orig_preview_path)
    scale = PREVIEW_SIZE / float(max(*orig.size))
    ##	preview = orig.resize((int(orig.size[0]*scale), int(orig.size[1]*scale)), Image.BICUBIC)
    preview = orig.resize(
        (int(orig.size[0] * scale), int(orig.size[1] * scale)),
        Image.ANTIALIAS)
    preview.save(preview_path + '.jpg')

    preview_metadata = pyexiv2.ImageMetadata(preview_path + '.jpg')
    preview_metadata.read()
    metadata.copy(preview_metadata)
    preview_metadata.write()

    # generate thumb and save to thumb dir...
    thumb_path = os.path.join(ARCHIVE_PATH, THUMBS_DIR, file_name_base)
    preview.thumbnail((THUMB_SIZE, THUMB_SIZE), Image.ANTIALIAS)
    preview.save(thumb_path + '.jpg')

    thumb_metadata = pyexiv2.ImageMetadata(thumb_path + '.jpg')
    thumb_metadata.read()
    metadata.copy(thumb_metadata)
    thumb_metadata.write()
Ejemplo n.º 8
0
def copy_tags(raw_filename, undistorted_filename):
    metadata_raw = pyexiv2.ImageMetadata(raw_filename)
    metadata_raw.read()
    metadata_undistorted = pyexiv2.ImageMetadata(undistorted_filename)
    metadata_undistorted.read()
    metadata_raw.copy(metadata_undistorted, comment=False)
    metadata_undistorted.write()
Ejemplo n.º 9
0
def compNewVals(p_file_1, p_file_2, p_file_3):
    #p_file_1 is unitialized, p_file_2 is initialized but unchanged, p_file_3's value was changed from p_file_2
    #this finds the new keys for file2 and file3
    #then it compares to see which values from those keys changed.
    f_metadata1 = pyexiv2.ImageMetadata(p_file_1)
    f_metadata1.read()
    f_metadata2 = pyexiv2.ImageMetadata(p_file_2)
    f_metadata2.read()
    f_metadata3 = pyexiv2.ImageMetadata(p_file_3)
    f_metadata3.read()
    f_newkeys = newKeys(p_file_1, p_file_2)
    f_vals = []
    for key in f_newkeys:
        if key == 'Xmp.xmp.CreateDate' or key == 'Xmp.MicrosoftPhoto.DateAcquired':
            f_vals.append("???")
            continue
        if (key in f_metadata2.exif_keys or \
            key in f_metadata2.iptc_keys or \
            key in f_metadata2.xmp_keys) and \
            (key in f_metadata3.exif_keys or \
             key in f_metadata3.iptc_keys or \
             key in f_metadata3.xmp_keys):      #if key really exists in both files
            if f_metadata2[key].value != f_metadata3[key].value:
                f_vals.append("Yes. Data changed")
            else:
                f_vals.append("No")
        else:
            f_vals.append("key missing")
    return f_vals
Ejemplo n.º 10
0
def whichParser(p_file_1, p_file_2):
    # prints value in file2 using all potential parsing methods
    f_metadata1 = pyexiv2.ImageMetadata(p_file_1)
    f_metadata1.read()
    f_metadata2 = pyexiv2.ImageMetadata(p_file_2)
    f_metadata2.read()
    f_newkeys = newKeys(p_file_1, p_file_2)
    f_vals = []
    for key in f_newkeys:
        if key == 'Exif.Photo.0xea1c' or key == 'Exif.Image.0xea1c':  #these values are too long and worthless
            f_vals.append("useless")
        elif key == 'Xmp.xmpMM.InstanceID' or key == 'Exif.Image.ExifTag':  # these values are also useless
            f_vals.append("useless")
        elif key == 'Xmp.xmp.CreateDate' or key == 'Xmp.MicrosoftPhoto.DateAcquired':
            f_vals.append("???")
        elif key=='Exif.Image.XPComment' or \
                key=='Exif.Image.XPSubject' or \
                key=='Exif.Image.XPTitle' or \
                key=='Exif.Image.XPKeywords' or \
                key=='Exif.Image.XPAuthor':
            f_vals.append(
                "MetadataManager.raw_to_cleanStr(f_metadata2[key].value)")
        elif key == key == 'Exif.Image.XMLPacket':
            f_vals.append(
                "pyexiv2.utils.undefined_to_string(f_metadata2[key].value)")
        elif key=='Xmp.dc.description' or \
                key=='Xmp.dc.title':
            f_vals.append("f_metadata2[key].value['x-default']")
        else:
            f_vals.append("f_metadata2[key].value")
    return f_vals
Ejemplo n.º 11
0
def shrinkIfNeededByPIL(path, maxDimension):
    if imageMaxDimensionByPIL(path) > maxDimension:
        print "-> shrinking " + path
        imagePath = getTempPath(path)
        img = Image.open(path)
        (w, h) = img.size
        if (w > h):
            img2 = img.resize((maxDimension, (h * maxDimension) / w),
                              Image.ANTIALIAS)
        else:
            img2 = img.resize(((w * maxDimension) / h, maxDimension),
                              Image.ANTIALIAS)
        img2.save(imagePath, 'JPEG', quality=99)

        # now copy EXIF data from original to new
        if HAS_PYEXIV2:
            # Method 1: use PYEXIV2
            src_image = pyexiv2.ImageMetadata(path)
            src_image.read()
            dst_image = pyexiv2.ImageMetadata(imagePath)
            dst_image.read()
            src_image.copy(dst_image, exif=True)
            # overwrite image size based on new image
            dst_image["Exif.Photo.PixelXDimension"] = img2.size[0]
            dst_image["Exif.Photo.PixelYDimension"] = img2.size[1]
            dst_image.write()
        elif HAS_EXIF:
            # Method 2: use EXIFTOOL
            subprocess.call(
                [exifTool, "-q", "-q", "-tagsfromfile", path, imagePath])

        return imagePath
    return path
Ejemplo n.º 12
0
def read_metadata_temp(filename):
    try:
        image = pyexiv2.ImageMetadata(filename)
        image.read()
        temp = None
    except (IOError, UnicodeDecodeError):
        temp = system.TempFile(suffix=os.path.splitext(filename)[-1])
        shutil.copy2(filename, temp.path)
        image = pyexiv2.ImageMetadata(temp.path)
        image.read()
    return image, temp
Ejemplo n.º 13
0
def match_metadata(image1_path, image2_path):
    """Compare images metadata"""
    try:
        import pyexiv2
        image1 = pyexiv2.ImageMetadata(image1_path)
        image1.read()
        image2 = pyexiv2.ImageMetadata(image2_path)
        image2.read()
        metadata1 = sorted([(key, image1[key].value) for key in image1.exif_keys])
        metadata2 = sorted([(key, image2[key].value) for key in image2.exif_keys])
        return metadata1 == metadata2
    except IOError:
        return True
Ejemplo n.º 14
0
def copyMetadata(imgSource, imgDest):

    #Copies over all metadata from one image to another

    metaSource = pyexiv2.ImageMetadata(imgSource)
    metaSource.read()

    metaDest = pyexiv2.ImageMetadata(imgDest)
    metaDest.read()
    metaSource.copy(metaDest, comment=False)
    metaDest.write()

    return
Ejemplo n.º 15
0
def copy(im1, im2):
    """
    Copies metadata from im1 to im2
    :param im1: string containing image1 filename
    :param im2: string containing image2 filename
    """
    meta1 = pyexiv2.ImageMetadata(im1)
    meta2 = pyexiv2.ImageMetadata(im2)

    meta1.read()
    meta2.read()

    meta1.copy(meta2)
    meta2.write(preserve_timestamps=True)
Ejemplo n.º 16
0
def move_date_taken(sql, photoids, dtfix, giventime):
    if not sql is None:
        logging.debug('Getting photo ids from database.')
        photoids = get_int_list_from_database(sql)

    if not isinstance(photoids, list):
        photoids = photoids.split(',')

    photoids = [int(i) for i in photoids]
    setidtoset, photoidtophoto = get_local_sets_and_photos()
    # Ensure that all photos have been loaded by constructing a dictionary.

    photoidtolocalphoto = dict([[id, os.path.join(photorootdir, photoidtophoto[id][0][0], photoidtophoto[id][0][1])] for id in photoids])
    datekeys = ['Exif.Photo.DateTimeOriginal', 'Exif.Photo.DateTimeDigitized']
    photoidtodatetime = dict()
        
    for id in photoidtolocalphoto:
        metadata = pyexiv2.ImageMetadata(photoidtolocalphoto[id])
        metadata.read()
        for datekey in datekeys:
            if datekey in metadata.exif_keys:
                dt = metadata[datekey].value
                if id not in photoidtodatetime:
                    photoidtodatetime[id] = dt
                elif dt != photoidtodatetime[id]:
                    raise Exception('Different dates in photo.')
        if id not in photoidtodatetime:
            if giventime is not None:
                photoidtodatetime[id] = giventime
            else:
                raise 'No take date found from photo'
    for id in photoidtolocalphoto:
        logging.debug('Changing taken dates of photo %s %s.' % (id, photoidtolocalphoto[id]))
        metadata = pyexiv2.ImageMetadata(photoidtolocalphoto[id])
        metadata.read()

        dt = photoidtodatetime[id]
        if giventime is None:
            dt = dt + dtfix
        for datekey in datekeys:
            if datekey in metadata.exif_keys:
                metadata[datekey].value = dt
            else:
                metadata[datekey] = pyexiv2.ExifTag(datekey, dt)
            metadata.write()

    for id in photoidtolocalphoto:
        logging.debug('Replacing photo %s ''%s''.' % (id, photoidtolocalphoto[id]))
        flickr_api.Upload.replace(photo_id = id, async = False, photo_file = photoidtolocalphoto[id])
Ejemplo n.º 17
0
def copy_image_metadata(source_file, dest_file):
    source_metadata = pyexiv2.ImageMetadata(source_file)
    source_metadata.read()

    dest_metadata = pyexiv2.ImageMetadata(dest_file)
    dest_metadata.read()

    for key in source_metadata.exif_keys:
        tag = source_metadata[key]
        try:
            dest_metadata[key] = pyexiv2.ExifTag(key, tag.value)
        except:
            pass

    dest_metadata.write()
Ejemplo n.º 18
0
def get_exif_data(photo):
    """
    NOTE: these attributes are not escaped
    """
    try:
        photo_exif = pyexiv2.ImageMetadata(photo)
        photo_exif.read()
    except Exception:
        raise

    yield ('mime:exif', photo_exif.mime_type)
    yield ('width', photo_exif.dimensions[0])
    yield ('height', photo_exif.dimensions[1])
    #yield ('dimensions', photo_exif.dimensions)
    yield ('comment', photo_exif.comment)

    if not photo_exif.keys():
        yield ('hasExif', False)
        yield ('a', 'Image')
        return
    else:
        yield ('hasExif', True)
        yield ('a', 'Photo')

    for (k, v) in photo_exif.iteritems():
        if 'date' in k.lower():
            yield (k, v.value.isoformat())
        else:
            yield (k, v.raw_value)
Ejemplo n.º 19
0
    def __openFile(self):

        try:
            self.metaData = pyexiv2.ImageMetadata(self.pathFile)
            self.__extractMetadata()
        except:
            self.metaDictionary["Error"] = "Isn't JPG File"
Ejemplo n.º 20
0
  def set_gps_location(self, file_name, lat, lng):
    """Adds GPS position as EXIF metadata
    Keyword arguments:
    file_name -- image file 
    lat -- latitude (as float)
    lng -- longitude (as float)
    """
    lat_deg = self.to_deg(lat, ["S", "N"])
    lng_deg = self.to_deg(lng, ["W", "E"])
    
    print (lat_deg)
    print (lng_deg)
    
    # convert decimal coordinates into degrees, munutes and seconds
    exiv_lat = (pyexiv2.Rational(lat_deg[0]*60+lat_deg[1],60),pyexiv2.Rational(lat_deg[2]*100,6000), pyexiv2.Rational(0, 1))
    exiv_lng = (pyexiv2.Rational(lng_deg[0]*60+lng_deg[1],60),pyexiv2.Rational(lng_deg[2]*100,6000), pyexiv2.Rational(0, 1))

    exiv_image = pyexiv2.ImageMetadata("{}/{}".format(self.download_dir, file_name))
    exiv_image.read()
    exif_keys = exiv_image.exif_keys
    
    exiv_image["Exif.GPSInfo.GPSLatitude"] = exiv_lat
    exiv_image["Exif.GPSInfo.GPSLatitudeRef"] = lat_deg[3]
    exiv_image["Exif.GPSInfo.GPSLongitude"] = exiv_lng
    exiv_image["Exif.GPSInfo.GPSLongitudeRef"] = lng_deg[3]
    exiv_image["Exif.Image.GPSTag"] = 654
    exiv_image["Exif.GPSInfo.GPSMapDatum"] = "WGS-84"
    exiv_image["Exif.GPSInfo.GPSVersionID"] = '2 0 0 0'
    
    exiv_image.write()
Ejemplo n.º 21
0
    def load_images(self):
        files = []
        self.pictures = []
        path = self.image_dir
        for file in os.listdir(path):
            if fnmatch.fnmatch(file, '*.jpg') or fnmatch.fnmatch(
                    file, '*.JPG'):
                files.append(file)
        files.sort()
        last_trigger = 0.0
        interval = 0
        for f in files:
            name = path + "/" + f
            print name
            exif = pyexiv2.ImageMetadata(name)
            exif.read()
            #print exif.exif_keys
            strdate, strtime = str(exif['Exif.Image.DateTime'].value).split()
            year, month, day = strdate.split('-')
            formated = year + "/" + month + "/" + day + " " + strtime + " UTC"
            result, unixtimestr = commands.getstatusoutput('date -d "' +
                                                           formated +
                                                           '" "+%s"')
            unixtime = float(unixtimestr)
            # print f + ": " + strdate + ", " + strtime + ", " + unixtimestr

            if last_trigger > 0.0:
                interval = unixtime - last_trigger

            self.pictures.append((unixtime, interval, f))

            last_trigger = unixtime

        print "number of images = " + str(len(self.pictures))
Ejemplo n.º 22
0
def EXIV2Meta(img):
    '''

	Return a list of tuples of all the EXIF, IPTC and XMP metadata in a file.
	
	Usage:
		from picasa3meta import exiv2meta

		metaData = exiv2meta.EXIV2Meta("/path/to/file.jpg")

		for key,value in metaData:
			print "%s : %s"%(key,value)

	Exif keys will return the human_value if possible, otherwise the raw_value.

	Iptc keys will return the raw_value first, if that fails, just value

	Xmp keys may be dict objects.  If it is a dict, return a comma separated
	list of the values.  Otherwise, try the raw_value first, then just value.

	'''

    try:
        metadata = pyexiv2.ImageMetadata(img)
        metadata.read()
    except:
        return zip(['error'], ['%s is not an image' % img])
    else:
        ret = []

        for K in metadata.exif_keys:
            try:
                ret.append(metadata[K].human_value)
            except:
                ret.append(metadata[K].raw_value)

        for K in metadata.iptc_keys:
            try:
                ret.append(metadata[K].raw_value[0])
            except:
                ret.append(metadata[K].value[0])

        for K in metadata.xmp_keys:
            if type(metadata[K].raw_value) == dict:
                # if the xmp key is a dict, return it as a comma separated list.
                nret = ""
                for KK in metadata[K].raw_value:
                    if len(nret) > 1:
                        nret = nret + ","
                    nret = nret + metadata[K].raw_value[KK]
                ret.append(nret)
            else:
                try:
                    ret.append(metadata[K].raw_value)
                except:
                    ret.append(metadata[K].value)

        # zip the keys and values into a list of tuples and return it
        return zip(metadata.exif_keys + metadata.iptc_keys + metadata.xmp_keys,
                   ret)
Ejemplo n.º 23
0
    def __getitem__(self, key):
        if not hasattr(self, '_metadata'):
            self._metadata = pyexiv2.ImageMetadata(self._fn)
            self._metadata.read()

        tag = self._metadata[key]
        return tag.value
Ejemplo n.º 24
0
 def _read_iptc_tags(filename, path):
     """
     method to read IPTC tags
     :param filename: filename of image
     :param path: path to image
     :return: [{'iptc_key': iptc key, 'tags': ['tag 1', 'tag 2']}] | False
     """
     try:
         url = os.path.join(path, filename)
         meta = pyexiv2.ImageMetadata(os.path.join(url))
         meta.read()
         iptc_keys = meta.iptc_keys or []
         image_data = []
         if iptc_keys:
             for key in iptc_keys:
                 tag = meta[key]
                 image_data.append({
                     'iptc_key': key,
                     'tags': tag.raw_value or []
                 })
         # else:
         #     image_data.append({'iptc_key': '', 'tags': []})
         return image_data
     except (IOError, KeyError, Exception) as e:
         print(f'An error occurred in read_iptc_tags: {e}')
         return False
Ejemplo n.º 25
0
def list_jpg(directory, camid=None):
    """ Search for all the jpg found in a folder and all the subfolders

	Return a list of list containing the camid, the complete path of the
	picture (string), and its DatetimeOriginal (datetime object from the Exif header)
	[['camid', '/mypath/mydirectory/mypicture.jpg', 'datetime.datetime']]
	"""

    file_list = []
    for root, subfolders, files in os.walk(directory):
        file_list += [
            os.path.join(root, filename) for filename in files
            if filename.lower().endswith(".jpg")
        ]
    files = []
    # get DateTimeOriginal data from the images and sort the list by timestamp
    for filepath in file_list:
        metadata = pyexiv2.ImageMetadata(filepath)
        metadata.read()
        try:
            t = metadata["Exif.Photo.DateTimeOriginal"].value
            # print t
            # print type(t)
            # s = metadata["Exif.Photo.SubSecTimeOriginal"].value
            files.append([camid, filepath, t])
        except KeyError, e:
            # if any of the required tags are not set the image is not added to the list
            print("Skipping {0}: {1}".format(filename, e))
Ejemplo n.º 26
0
    def set_gps_location(self, file_name, lat, lng, alt):
        """Adds GPS position as EXIF metadata

           Keyword arguments:
           file_name -- image file
           lat -- latitude (as float)
           lng -- longitude (as float)

           """
        lat_deg = self.to_deg(lat, ["S", "N"])
        lng_deg = self.to_deg(lng, ["W", "E"])

        # convert decimal coordinates into degrees, munutes and seconds
        exiv_lat = (pyexiv2.Rational(lat_deg[0] * 60 + lat_deg[1], 60),
                    pyexiv2.Rational(lat_deg[2] * 100,
                                     6000), pyexiv2.Rational(0, 1))
        exiv_lng = (pyexiv2.Rational(lng_deg[0] * 60 + lng_deg[1], 60),
                    pyexiv2.Rational(lng_deg[2] * 100,
                                     6000), pyexiv2.Rational(0, 1))
        metadata = pyexiv2.ImageMetadata(file_name)

        metadata.read()
        ##    exif_keys = metadata.exif_keys

        metadata["Exif.GPSInfo.GPSLatitude"] = exiv_lat
        metadata["Exif.GPSInfo.GPSLatitudeRef"] = lat_deg[3]
        metadata["Exif.GPSInfo.GPSLongitude"] = exiv_lng
        metadata["Exif.GPSInfo.GPSLongitudeRef"] = lng_deg[3]
        metadata["Exif.GPSInfo.GPSAltitude"] = pyexiv2.Rational(alt, 1)
        metadata["Exif.Image.GPSTag"] = 654
        metadata["Exif.GPSInfo.GPSMapDatum"] = "WGS-84"
        metadata["Exif.GPSInfo.GPSVersionID"] = '2 0 0 0'
        metadata.write()
Ejemplo n.º 27
0
    def read_metadata(self):
        """
        Read EXIF or XMP data from file. Convert to Python dict.
        """
        # Xmp.xmp.CreateDate
        # XXX: We already know file exists 'cuz we found it.
        img_md = pyexiv2.ImageMetadata("{}".format(self.src_fn_fq))
        img_md.read()

        metadata = {}

        if (self.image_type == photo_rename.IMAGE_TYPE_PNG):
            metadata_keys = [md_key for md_key in img_md.xmp_keys]
        else:
            metadata_keys = [md_key for md_key in img_md.exif_keys]

        for exifkey in metadata_keys:
            tag = img_md[exifkey].raw_value
            #self.logger.debug(exifkey)
            #self.logger.debug("{}: {}".format(exifkey, tag))
            metadata[exifkey] = tag

        if (len(metadata) == 0):
            raise Exception("{0} has no EXIF data.".format(self.src_fn))

        return metadata
Ejemplo n.º 28
0
def list_images(directory):
    ''' 
    Create a list of image tuples sorted by capture timestamp.
    @param directory: directory with JPEG files 
    @return: a list of image tuples with time, directory, lat,long...
    '''
    file_list = []
    for root, sub_folders, files in os.walk(directory):
        file_list += [
            os.path.join(root, filename) for filename in files
            if filename.lower().endswith(".jpg")
        ]

    files = []
    # get GPS data from the images and sort the list by timestamp
    for filepath in file_list:
        metadata = pyexiv2.ImageMetadata(filepath)
        metadata.read()
        try:
            t = metadata["Exif.Photo.DateTimeOriginal"].value
            lat = metadata["Exif.GPSInfo.GPSLatitude"].value
            latRef = metadata["Exif.GPSInfo.GPSLatitudeRef"].value
            lon = metadata["Exif.GPSInfo.GPSLongitude"].value
            lonRef = metadata["Exif.GPSInfo.GPSLongitudeRef"].value
            direction = metadata["Exif.GPSInfo.GPSImgDirection"].value
            dmslat = DMStoDD(lat[0], lat[1], lat[2], latRef)
            dmslon = DMStoDD(lon[0], lon[1], lon[2], lonRef)
            files.append(
                (filepath, int(float(lat[0])), int(float(lat[1])),
                 float(lat[2]), latRef, int(float(lon[0])), int(float(lon[1])),
                 float(lon[2]), lonRef, float(direction)))
        except KeyError, e:
            # if any of the required tags are not set the image is not added to the list
            print("Skipping {0}: {1}".format(filename, e))
Ejemplo n.º 29
0
def image_write(image_filename, text_to_print):
    # function to write date/time stamp directly on top or bottom of images.
    FOREGROUND = (255, 255, 255)  # rgb settings for white text foreground
    text_colour = "White"
    font_size = 20

    # centre text and compensate for graphics text being wider
    x = int((image_width / 2) - (len(text_to_print) * font_size / 4))
    if image_text_bottom:
        y = (image_height - 50)  # show text at bottom of image
    else:
        y = 10  # show text at top of image
    TEXT = text_to_print
    font_path = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'
    font = ImageFont.truetype(font_path, font_size, encoding='unic')
    text = TEXT.decode('utf-8')

    # Read exif data since ImageDraw does not save this metadata
    metadata = pyexiv2.ImageMetadata(image_filename)
    metadata.read()

    img = Image.open(image_filename)
    draw = ImageDraw.Draw(img)
    # draw.text((x, y),"Sample Text",(r,g,b))
    draw.text((x, y), text, FOREGROUND, font=font)
    img.save(image_filename)
    metadata.write()  # Write previously saved exif data to image file
    msgStr = " Image Saved - " + text_to_print
    show_message("image_write ", msgStr)
    return
Ejemplo n.º 30
0
def copy_photos(filename: str, source_folder: str, dest_folder: str):
    try:
        metadata = pyexiv2.ImageMetadata(source_folder + filename)
        metadata.read()
        tag = metadata['Exif.Image.DateTime']
        creation_date = tag.value.date()

        del metadata
        del tag

        folder_name = str(creation_date)

        new_directory = dest_folder + folder_name + '/'

        try:
            if not os.path.exists(new_directory):
                os.makedirs(new_directory)
            else:
                logger.info('folder ' + new_directory + ' already exists!')
        except:
            logger.info('folder ' + new_directory + ' could not be created!')

        try:
            if not os.path.isfile(new_directory + filename):
                shutil.copy2(source_folder + filename, new_directory)
            else:
                logger.info('file ' + filename + ' already exists')
        except:
            logger.info('file ' + filename + ' could not be moved')
    except:
        logger.info('file ' + filename + ' could not be copied')