def tag_image(file_name, Modules, Experiment, Category, Description): if pyexivexists: metadata = pyexiv2.Image(file_name) try: _dict = metadata.read_exif() # print(_dict) except IOError: print("Not an image") else: _dict['Exif.Image.Software'] = Modules _dict['Exif.Image.Make'] = Experiment _dict['Exif.Photo.MakerNote'] = Category _dict['Exif.Image.ImageDescription'] = Description # metadata.modify_all({"EXIF":_dict}) metadata.modify_exif(_dict) # print(metadata.read_all()) # metadata.clear_all() finally: meta_reload = pyexiv2.Image(file_name) print(meta_reload.read_exif()) # print(metadata.read_all()) # metadata.clear_all() else: print("PyExiv not present") return 1
def match_metadata(image1_path, image2_path): """Compare images metadata""" try: import pyexiv2 image1 = pyexiv2.Image(image1_path) image1.readMetadata() image2 = pyexiv2.Image(image2_path) image2.readMetadata() metadata1 = sorted([(key, image1[key]) for key in image1.exifKeys()]) metadata2 = sorted([(key, image2[key]) for key in image2.exifKeys()]) return metadata1 == metadata2 except IOError: return True
def process(folder, params): import pyexiv2 class AttributeMapper(RecursiveAttributes): def __init__(self, keys, image): super(AttributeMapper, self).__init__() for key in keys: setattr(self, key, image[key]) # setup default mapping + local overrides mapping = ImageMetadataPyExiv2.DEFAULT_MAPPING.copy() mapping.update(params.get('mapping', {})) # loop through all media resources node = params['node'] if node.type == 'media': for resource in node.walk_resources(): try: image = pyexiv2.Image(resource.source_file.path) image.readMetadata() except: continue # setup all retrieved keys in resource.meta keys = set(image.exifKeys() + image.iptcKeys()) resource.meta = AttributeMapper(keys, image) # use the mapping to add easier access to some attributes for key, attr in mapping.items(): if key in keys: setattr(resource.meta, attr, getattr(resource.meta, key))
def getMetadataFromPath(cls, path): """Return metadata from the given file, if it exists. Supports JPG/EXIF. Credits: https://github.com/LeoHsiao1/pyexiv2#usage Return dict (empty if no metadata available) """ result = {} # TODO: verify it's JPG try: Logger.debug( 'Image.getMetadataFromPath(): Reading metadata from "%s"' % path) image = pyexiv2.Image(path) result = image.read_exif( encoding='ISO-8859-1' ) # {'Exif.Image.DateTime': '2019:06:23 19:45:17', 'Exif.Image.Artist': 'TEST', ...} # image.close() # recommended to prevent memory leak, but does not exist Logger.debug('Image.getMetadataFromPath(): Metadata is %s' % result) except Exception as e: Logger.error( 'Image.getMetadataFromPath(): Exception while reading metadata:\n%s' % e) return (result)
def get_metadata(input_file): img = pyexiv2.Image(input_file) exif = img.read_exif() xmp = img.read_xmp() focal_length = convert_string_to_float( exif['Exif.Photo.FocalLength']) / 1000 # unit: m orientation = int(exif['Exif.Image.Orientation']) maker = exif["Exif.Image.Make"] longitude = convert_dms_to_deg(exif["Exif.GPSInfo.GPSLongitude"]) latitude = convert_dms_to_deg(exif["Exif.GPSInfo.GPSLatitude"]) if exif["Exif.Image.Make"] == "DJI": altitude = float(xmp['Xmp.drone-dji.RelativeAltitude']) roll = float(xmp['Xmp.drone-dji.GimbalRollDegree']) pitch = float(xmp['Xmp.drone-dji.GimbalPitchDegree']) yaw = float(xmp['Xmp.drone-dji.GimbalYawDegree']) elif exif["Exif.Image.Make"] == "samsung": altitude = convert_string_to_float(exif['Exif.GPSInfo.GPSAltitude']) roll = float(xmp['Xmp.DLS.Roll']) * 180 / np.pi pitch = float(xmp['Xmp.DLS.Pitch']) * 180 / np.pi yaw = float(xmp['Xmp.DLS.Yaw']) * 180 / np.pi else: altitude = 0 roll = 0 pitch = 0 yaw = 0 eo = np.array([longitude, latitude, altitude, roll, pitch, yaw]) return focal_length, orientation, eo, maker
def _read_exif(filespec): info = ImageInfo() info.filespec = filespec info.filetype = "exif" info.isfloat = False img = pyexiv2.Image(filespec) exif = img.read_exif() subimages = ["Image", "SubImage1", "SubImage2", "SubImage3"] widths = [exif.get(f"Exif.{sub}.ImageWidth") for sub in subimages] widths = [int(w or 0) for w in widths] # None => 0 maximg = subimages[np.argmax(widths)] # use the largest sub-image info.cfa_raw = exif.get(f"Exif.{maximg}.PhotometricInterpretation") in [ '32803', '34892' ] info.width = int(exif.get(f"Exif.{maximg}.ImageWidth")) info.height = int(exif.get(f"Exif.{maximg}.ImageLength")) info.nchan = int(exif.get(f"Exif.{maximg}.SamplesPerPixel")) info.bitdepth = exif.get(f"Exif.{maximg}.BitsPerSample") info.orientation = int(exif.get(f"Exif.{maximg}.Orientation") or 1) exif_to_rot90 = {1: 0, 2: 0, 3: 2, 4: 0, 5: 1, 6: 3, 7: 3, 8: 1} if info.orientation in exif_to_rot90: info.rot90_ccw_steps = exif_to_rot90[info.orientation] bitdepths = tuple( int(el) for el in info.bitdepth.split(" ")) # string => tuple of ints info.bitdepth = bitdepths[0] info = _complete(info) return info
def read_metadata_local(inputfile, verbose): """ EXIF and IPTC metadata extraction and printing from images @param inputfile: path to the image @type inputfile: string @param verbose: verbosity @type verbose: int @rtype: dict @return: dictionary with metadata """ # Load the image image = pyexiv2.Image(inputfile) # Read the metadata image.readMetadata() image_info = {} # EXIF metadata for key in image.exifKeys(): image_info[key] = image.interpretedExifValue(key) # IPTC metadata for key in image.iptcKeys(): image_info[key] = repr(image[key]) # Return the dictionary return image_info
def update_xmp_metadata(image, categories, options): """ Update the XMP metadata for a single image """ filename = '' img_path = '' try: filename = image['file'] if options.remove_path != None and len(options.remove_path) > 0: filename = filename.replace(options.remove_path, '') img_path = os.path.join(options.image_folder, filename) assert os.path.isfile(img_path), 'Image {} not found'.format(img_path) image_categories = [] for detection in image['detections']: cat = categories[detection['category']] if cat not in image_categories: image_categories.append(cat) img = pyexiv2.Image(r'{0}'.format(img_path)) img.modify_xmp({'Xmp.lr.hierarchicalSubject': image_categories}) except Exception as e: s = 'Error processing image {}: {}'.format(filename, str(e)) print(s) traceback.print_exc() write_status(options, s)
def append_keywords(self, to_append: List[str]) -> int: """ Appends a list of keywords to the keyword list after checking for duplicates. :param to_append: Keywords to append :return: Number of keywords that were appended. """ if not self.md_init_complete: self.init_metadata() initial_kw: List[str] = self.get_keywords() current = initial_kw.copy() new_kws = 0 for keyword in to_append: if keyword not in current: current.append(keyword) new_kws += 1 if current == initial_kw: return 0 current_string: str = ",".join(current) patch = {self.keyword_field_name: current_string} loaded = pe2.Image(self.filepath) loaded.modify_iptc(patch, encoding=ImageFile.normal_encoding) loaded.close() self.iptc[self.keyword_field_name] = current_string return new_kws
def AddComment(filename): with pyexiv2.Image(filename) as img: valueMsg = input("Input your msg (q to quit) =" ) if not valueMsg == 'q': if valueMsg != '': img.modify_comment(valueMsg) print("write comment is success!")
def clear_keywords(self): patch = {self.keyword_field_name: ""} loaded = pe2.Image(self.filepath) loaded.modify_iptc(patch, encoding=ImageFile.normal_encoding) loaded.close() self.iptc[self.keyword_field_name] = ""
def process_image(filename): image = pyexiv2.Image(filename) image.readMetadata() lon = rational2deg(image['Exif.GPSInfo.GPSLongitude']) if 'W' == image['Exif.GPSInfo.GPSLongitudeRef']: lon = -lon lat = rational2deg(image['Exif.GPSInfo.GPSLatitude']) if 'S' == image['Exif.GPSInfo.GPSLatitudeRef']: lat = -lat dt = image['Exif.Image.DateTime'] thumbname = filename.split('.')[0] + '-thumbnail.jpg' im = Image.open(filename) im.thumbnail((150, 150)) im.save(thumbname, 'JPEG') indent = '\t\t ' description = [ indent + filename, indent + str(dt), indent + 'Longitude %s' % lon, indent + 'Latitude %s' % lat, indent + '<img src="' + thumbname + '"/>', ] description = '<br/>\n'.join(description) placemark = kml_placemark(lon, lat, name=dt.strftime('%H%M%S'), description=description) return placemark
def save_description(self, image_path, string): print("save: " + image_path + " :: " + string) img = pyexiv2.Image(image_path, encoding='utf-8') userdata = {'Xmp.dc.desciption': string} img.modify_xmp(userdata) img.close() self.reload_gallery()
def readmeta(file): import pyexiv2 i = pyexiv2.Image(file) i.readMetadata() def item(image, key, value): try: truevalue = unicode(image[value]) tmp = image[value] if unicode(image[value].__class__) == 'pyexiv2.Rational': fvalue = float(tmp.numerator) / tmp.denominator if fvalue >= 1: truevalue = "%.1f" % fvalue return '<b>%s:</b> %s ' % (key, truevalue) except: return '' d = '' d += item(i, 'Date', 'Exif.Photo.DateTimeOriginal') d += item(i, 'Camera', 'Exif.Image.Model') d += item(i, 'Exposure time', 'Exif.Photo.ExposureTime') d += item(i, 'F-number', 'Exif.Photo.FNumber') d += item(i, 'ISO rating', 'Exif.Photo.ISOSpeedRatings') d += item(i, 'Focal length', 'Exif.Photo.FocalLength') try: date = i['Exif.Photo.DateTimeOriginal'] except: date = None return (d, date)
def update_file_info(self, fileobj): if fileobj.get_uri_scheme() != 'file': return filename = urllib.unquote(fileobj.get_uri()[7:]) # jpeg EXIF handling (also try running it on other image types, if only for the image size) if fileobj.is_mime_type('image/jpeg') or fileobj.is_mime_type( 'image/png') or fileobj.is_mime_type( 'image/gif') or fileobj.is_mime_type('image/bmp'): try: img = pyexiv2.Image(filename) img.readMetadata() fileobj.add_string_attribute( 'exif_pixeldimensions', str(img['Exif.Photo.PixelXDimension']) + 'x' + str(img['Exif.Photo.PixelYDimension'])) except: # no exif data? fileobj.add_string_attribute('exif_pixeldimensions', "") # try read image info directly try: im = Image.open(filename) fileobj.add_string_attribute( 'pixeldimensions', str(im.size[0]) + 'x' + str(im.size[1])) except: fileobj.add_string_attribute('pixeldimensions', "[image read error]") else: fileobj.add_string_attribute('exif_pixeldimensions', '') fileobj.add_string_attribute('pixeldimensions', '') self.get_columns()
def get_has_data(self, full_path): """ Return True if the gramplet has data, else return False. """ # pylint: disable=E1101 if OLD_API: # prior to v0.2.0 try: metadata = pyexiv2.Image(full_path) except IOError: return False metadata.readMetadata() for tag in TAGS: if tag[1] in metadata.exifKeys(): return True else: # v0.2.0 and above metadata = pyexiv2.ImageMetadata(full_path) try: metadata.read() except IOError: return False for tag in TAGS: if tag[1] in metadata.exif_keys: return True return False
def _get_some_exifs(filename, key_list): try: if not isinstance(key_list, list): return # with open(filename.encode('utf-8'), 'rb') as f: # tags = exifread.process_file(f) with pyexiv2.Image(filename, encoding='gbk') as img: tags = img.read_exif() # img = Image.open(filename) # tags = {TAGS[k]: v for k, v in img._getexif().items() if k in TAGS} # print(tags) if tags: my_dict = {} for each in key_list: my_dict[r"f'{each}'"] = tags[each] # pat = re.compile(f'{each}', re.I) # 不区分大小写 # print(pat) # for tag, value in tags.items(): # # print(re.match(pat, tag)) # if re.match(each, tag): # my_dict[each] = value return my_dict return None except Exception as e: return f"ERROR: {e}。"
def view_gps_location(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 = to_deg(lat, ["S", "N"]) lng_deg = 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)) exiv_lng = (pyexiv2.Rational(lng_deg[0] * 60 + lng_deg[1], 60), pyexiv2.Rational(lng_deg[2] * 100, 6000)) exiv_image = pyexiv2.Image(file_name) exiv_image.readMetadata() exif_keys = exiv_image.exifKeys() for key in exif_keys: print key, [exiv_image[key]]
def exiv_read(img_filepath): img = pyexiv2.Image(img_filepath) img.readMetadata() for k in img.exifKeys(): print "%s=%s" % (k, img[k]) print img['Exif.Image.DateTime'].hour print img['Exif.Image.DateTime'].minute print img['Exif.Image.DateTime'].second
def Modify_Photo_Coordinate(): for i in tqdm.tqdm(List_Box_Info, desc='完善照片信息', ncols=100): for photo_name in i['Box_Photos']: random_num = random.randint(1,99)/1000000 Obj_img = pyexiv2.Image(photo_name, 'gb2312') Dic_New_Coordinate = {'Exif.GPSInfo.GPSLongitude': DD2DMS(float(i['LONGITUDE']) + random_num), 'Exif.GPSInfo.GPSLatitude': DD2DMS(float(i['LATITUDE']) + random_num), 'Exif.GPSInfo.GPSLatitudeRef': 'N', 'Exif.GPSInfo.GPSLongitudeRef': 'E', } Obj_img.modify_exif(Dic_New_Coordinate) Obj_img.close()
def datecaption(fname): try: i = pyexiv2.Image(fname) i.readMetadata() return i['Exif.Image.DateTime'].strftime('%B %Y') except: print "%s: no exif"%fname return ''
def read_exif(file_name): if pyexivexists: metadata = pyexiv2.Image(file_name) try: _dict = metadata.read_exif() # print(_dict) except IOError: print("Not an image") else: meta_reload = pyexiv2.Image(file_name) print(meta_reload.read_exif()) print(metadata.read_all()) # metadata.clear_all() else: print("PyExiv not present") return 1
def open_image_exif_thumb(uri): if pyexiv2: try: pyexiv2_image = pyexiv2.Image(uri) pyexiv2_image.readMetadata() thumb_data = pyexiv2_image.getThumbnailData() if thumb_data: return imtools.open_image_data(thumb_data) except Exception, details: pass
def fromNameAndData(image_name, image_data): full_image_path = '{}/{}'.format(app.config['DATA_DIR'], image_name) Image.__save_to_disk(full_image_path, image_data) original_path = image_name metadata = pyexiv2.Image(full_image_path) caption = Image.__get_caption(metadata) date = Image.__get_date(metadata) location = Image.__get_location(metadata) keywords = Image.__get_keywords(metadata) return Image(original_path, caption, date, location, keywords)
def remove_exif(fn): try: img = pyexiv2.Image(fn) # data = img.read_exif(); print(data) img.clear_exif() img.clear_iptc() img.clear_xmp() img.close() except Exception as e: print('EXIF error on {}: {}'.format(fn, str(e)))
def init_metadata(self): """ Load IPTC metadata for this image. :return: Fields with data in them. """ file = pe2.Image(self.filepath) self.iptc = file.read_iptc(encoding=self.normal_encoding) self.exif = file.read_exif(encoding=self.normal_encoding) self.xmp = file.read_xmp(encoding=self.normal_encoding) file.close() self.md_init_complete = True
def imgExif(path): try: text = pytesseract.image_to_string(Image.open(path), lang='chi_sim') string = re.sub("[\s+\.\!\/_,$%^*(+\"\')]+|[+——()?【】“”!,。?、~@#¥%……&*()]+", "", text) print(string) img_tag = pyexiv2.Image(path) img_tag.modify_exif({"Exif.Image.ImageDescription": string}) img_tag.modify_iptc({"Iptc.Application2.Caption": string}) print('图片' + path + '写入成功') except Exception as e: print(e) print('图片' + path + '写入失败')
def process(self, _edObject=None): EDPluginExec.process(self) EDVerbose.DEBUG("EDPluginCopyExifv1_0.process") self.exifInfile = pyexiv2.Image(self.strInfile) self.exifOutfile = pyexiv2.Image(self.strOutfile) self.exifInfile.readMetadata() self.exifOutfile.readMetadata() for metadata in [ 'Exif.Image.Make', 'Exif.Image.Model', 'Exif.Photo.DateTimeOriginal', 'Exif.Photo.ExposureTime', 'Exif.Photo.FNumber', 'Exif.Photo.ExposureBiasValue', 'Exif.Photo.Flash', 'Exif.Photo.FocalLength', 'Exif.Photo.ISOSpeedRatings']: #for metadata in self.exifInfile.exifKeys(): try: self.exifOutfile[metadata] = self.exifInfile[metadata] except ValueError: EDVerbose.WARNING("ValueError in copying metadata %s in file %s, value: %s" % (metadata, self.strInfile, self.exifInfile[metadata])) #dcraw sets automatically the good orientation self.exifOutfile['Exif.Image.Orientation'] = 1 # save the name of the raw image self.exifOutfile["Exif.Photo.UserComment"] = self.strInfile self.exifOutfile.writeMetadata()
def ModifyImageFile(filename): image = pyexiv2.Image(filename) meta = image.read_exif() if 'Exif.Photo.DateTimeOriginal' in meta: date = meta['Exif.Photo.DateTimeOriginal'] print (date) date_time_obj = datetime.datetime.strptime(date, '%Y:%m:%d %H:%M:%S') date_time_obj = date_time_obj + datetime.timedelta(hours=3, minutes=0, seconds=0) print (date_time_obj) image.modify_exif({'Exif.Photo.DateTimeOriginal': date_time_obj.strftime('%Y:%m:%d %H:%M:%S')})
def setEXIF(fname, key, val): """Sets the given EXIF tag for the given filename""" try: im = pyexiv2.Image(fname) im.readMetadata() im[key] = val im.writeMetadata() except AttributeError: # must be newer version of pyexiv2 im = pyexiv2.ImageMetadata(fname) im.read() im[key] = val im.write()