def exif_copy( src, target): #transfers exif data from a source image to a target image with Image(r'{}'.format(src)) as img_src, Image( r'{}'.format(target)) as img_targ: exif_data = img_src.read_exif() #exif data (if present) img_targ.modify_exif(exif_data) iptc_data = img_src.read_iptc() #iptc data (if present) img_targ.modify_iptc(iptc_data) xmp_data = img_src.read_xmp() #xmp data (if present) img_targ.modify_xmp(xmp_data)
def setup_function(): if ENV.skip_test: pytest.skip() shutil.copy( ENV.original_img, ENV.test_img) # Before each test, make a temporary copy of the image ENV.img = Image(ENV.test_img)
def face_rec(fpath, names, known_faces, model='hog'): unknown_images = get_file_path(fpath) count = 0 total = len(unknown_images) for i in unknown_images: count += 1 try: im = Image(i) except: print('Pass ' + i) continue # im_xmp = im.read_xmp() # if 'Xmp.xmp.Keywords' in im_xmp.keys(): # continue final_labels = '' xmp_labels = dict() xmp_labels.setdefault('Xmp.xmp.Keywords', '') unknown = face_recognition.load_image_file(i, pixel=1000) face_loc = face_recognition.face_locations(unknown, model=model) unknown_face_encoding = face_recognition.face_encodings( unknown, known_face_locations=face_loc) for f in unknown_face_encoding: dis = face_recognition.face_distance(known_faces, f) min_dis = min(dis) if min_dis <= 0.5: idx = dis.tolist().index(min_dis) label = names[idx] + ',' xmp_labels['Xmp.xmp.Keywords'] = xmp_labels[ 'Xmp.xmp.Keywords'] + label im.modify_xmp(xmp_labels) final_labels = im.read_xmp()['Xmp.xmp.Keywords'] print( str(count) + '/' + str(total) + ' ' + i + ' added labels: ' + str(final_labels)) im.close()
def getInternalCalibrationMatrix(path): #Using the given info # CMOS长宽信息 w_c = 17.3 h_c = 13.0 # 读取图片的长宽信息 img = cv2.imread(path) h = img.shape[0] w = img.shape[1] print(w, h) # 从EXIF中读取焦距 i = Image(path) a, b = i.read_exif().get('Exif.Photo.FocalLength').split('/') fm = int(a) / int(b) f = w * fm / w_c # 计算内参信息 K = np.zeros((3, 3)) K[0][0] = f K[1][1] = f K[0][2] = w / 2 K[1][2] = h / 2 K[2][2] = 1 return K
def getAttributes(self, fileName, fileObject, fileStat, fileAttributes): try: img = Image(fileName) except: return False fileAttributes[u"class"] = u"image" mapper = Mapper(fileAttributes, img) mapper.assign({ 'Exif.Image.Make': u"image/make", 'Exif.Image.Model': u"image/make-model", 'Exif.Image.DateTime': ATTR_GENERIC_DATETIME, 'Exif.Image.XResolution': u"image/x-resolution", 'Exif.Image.YResolution': u"image/y-resolution", 'Exif.Photo.ExposureTime': u"photo/exposure-time", 'Exif.Photo.FNumber': u"photo/f-number", 'Exif.Photo.ISOSpeedRatings': u"photo/iso-speed-ratings", 'Exif.Photo.ShutterSpeedValue': u"photo/shutter-speed-value", 'Exif.Photo.ApertureValue': u"photo/aperture-value", 'Exif.Photo.ExposureBiasValue': u"photo/exposure-bias-value", 'Exif.Photo.MeteringMode': u"photo/metering-mode", 'Exif.Photo.Flash': u"photo/flash", 'Exif.Photo.FocalLength': u"photo/focal-length" })
def getPara_PICTURE_EXIF(self, standardPicDir): """ 从图像EXIF参数中获取相机参数 :param standardPicDir: 标准像片 :return: """ # CMOS长宽信息 w_c = 6.29 h_c = 5.21 # 读取图片的长宽信息 img = cv2.imread(standardPicDir) h = img.shape[0] w = img.shape[1] print(w, h) # 从EXIF中读取焦距 i = Image(standardPicDir) a, b = i.read_exif().get('Exif.Photo.FocalLength').split('/') fm = int(a) / int(b) f = w * fm / w_c # 计算内参信息 K = np.zeros((3, 3)) K[0][0] = f K[1][1] = f K[0][2] = w / 2 K[1][2] = h / 2 print(K)
def check_the_copy_of_img(diff, reference, method_name): """ Copy the image and check it, in case the modified data is not saved to disk. """ try: shutil.copy(ENV.test_img, ENV.test_img_copy) with Image(ENV.test_img_copy) as img: diff(reference, getattr(img, method_name)()) finally: os.remove(ENV.test_img_copy)
def read_exiv2_image(path) -> Image: """ Read an image with basic error handling. Note: Exiv2 ``RuntimeError`` usually means corrupted metadata. See: https://dev.exiv2.org/issues/637#note-1 """ try: return Image(path) except RuntimeError: logger.exception(f'Failed to read corrupted metadata from {path}') return None
def read_key_from_img(img_path): """拿到图像标签数据""" img = Image(img_path) img_info_dict = img.read_iptc() img.close() if "Iptc.Application2.Keywords" in img_info_dict: key_words = img_info_dict["Iptc.Application2.Keywords"] return key_words else: return None
def add_to_exif(known): for file_name, identified_names in known.items(): name_string = "" for each_name in identified_names: if name_string == "": name_string = each_name else: name_string += ", " + each_name copyfile(join(r"C:\Users\Book\Desktop\face recogniser\input_image", file_name), join(r"C:\Users\Book\Desktop\face recogniser\tagged_image", file_name)) i = Image(join(r"C:\Users\Book\Desktop\face recogniser\tagged_image", file_name)) i.modify_exif({"Exif.Image.Make": name_string})
def add_key_to_img(img_path, key_words): """往图像中写入标签数据,可以以逗号分隔,或者用 json 格式""" if isinstance(key_words, list) or isinstance( key_words, tuple) or isinstance(key_words, set): key_words = map(lambda x: str(x), key_words) key_words = ",".join(key_words) key_words_dict = {'Iptc.Application2.Keywords': key_words} img = Image(img_path) img.modify_iptc(key_words_dict) img.close()
def readMetadata(image): print("Resultados para "+image+ ' \n ') #indica en consola los metadatos file=open("metadatos.html","a") #Crea el archivo donde se exportan los metadatos, y dado el caso que ya exista, lo abre con el puntero en la ultima línea file.write(' \n Resultados para' + image + ' \n ') #Escribe en el archivo try: for (k,v) in PImage.open(image)._getexif().items(): #Por cada metadato extraido de la imagen print('%s = %s ' % (TAGS.get(k), v)) #Imprime en pantalla file.write('\n') file.write('\n %s = %s ' % (TAGS.get(k), v)) #Escribe en el archivo file.write('\n') #Salto de linea en el archivo with Image(image) as img: #Otros metadatos imprimidos en consola data=img.read_exif() data2=img.read_iptc() data3=img.read_raw_xmp() if data: print("Metadatos Exif") file.write(" \n Metadatos Exif \n ") file.write(' \n ') for key, value in data.items(): print (key, ":", value) file.write(key, ":", value) file.write('\n') if data2: print("Metadatos IPTC") file.write("\n Metadatos IPTC \n") file.write('\n') for key, value in data2.items(): print (key, ":", value) file.write(key, ":", value) file.write('\n') if data3: print("Metadatos RAW XMP") file.write("\n Metadatos RAW XMP \n ") file.write('\n') for key, value in data3.items(): print (key, ":", value) file.write(key, ":", value) file.write('\n') except: print ("Metadata no encontrada! \n ") file.write(" \n Metadata no encontrada \n ") file.write('\n') file.write('\n') file.close()
def read_exif(input_pic): img = Image(input_pic) data = img.read_exif() print("exif:", data) # data2 = img.read_iptc() # print("iptc:", data2) # data3 = img.read_xmp() # print("xmp:", data3) # data4 = img.read_raw_xmp() # print("raw_xmp:", data4) # data5 = img.read_comment() # print("comment:",data5) # data6 = img.read_icc() # print("icc:",data6) img.close() return data
def Process_img(path): image = Image(path) i_xmp = image.read_xmp() info = { 'GPSLatitude': i_xmp.get('Xmp.drone-dji.GpsLatitude'), 'GPSLongitude': i_xmp.get('Xmp.drone-dji.GpsLongtitude'), 'GPSAltitude': i_xmp.get('Xmp.drone-dji.AbsoluteAltitude'), 'GPSRelativeAltitude': i_xmp.get('Xmp.drone-dji.RelativeAltitude'), 'CameraRoll': i_xmp.get('Xmp.drone-dji.GimbalRollDegree'), 'CameraYaw': i_xmp.get('Xmp.drone-dji.GimbalYawDegree'), 'CameraPitch': i_xmp.get('Xmp.drone-dji.GimbalPitchDegree'), 'FlightRoll': i_xmp.get('Xmp.drone-dji.FlightRollDegree'), 'FlightYaw': i_xmp.get('Xmp.drone-dji.FlightYawDegree'), 'FlightPitch': i_xmp.get('Xmp.drone-dji.FlightPitchDegree'), 'SpeedX': i_xmp.get('Xmp.drone-dji.FlightXSpeed'), 'SpeedY': i_xmp.get('Xmp.drone-dji.FlightYSpeed'), 'SpeedZ': i_xmp.get('Xmp.drone-dji.FlightZSpeed'), 'CalibratedOpticalCenterX': i_xmp.get('Xmp.drone-dji.CalibratedOpticalCenterX'), 'CalibratedOpticalCenterY': i_xmp.get('Xmp.drone-dji.CalibratedOpticalCenterY'), 'CalibratedOpticalFocalLength': i_xmp.get('Xmp.drone-dji.CalibratedFocalLength'), } i_exif = image.read_exif() info['XResolution'] = i_exif.get('Exif.Image.XResolution') info['YResolution'] = i_exif.get('Exif.Image.YResolution') info['PixelXDimension'] = i_exif.get('Exif.Photo.PixelXDimension') info['PixelYDimension'] = i_exif.get('Exif.Photo.PixelYDimension') info['FocalLength'] = i_exif.get('Exif.Photo.FocalLength') info['FocalLengthIn35mmFilm'] = i_exif.get( 'Exif.Photo.FocalLengthIn35mmFilm') return info
def mag_calc(image, distance, rings): with Image(r'{}'.format(image)) as img: exif_data = img.read_exif() #take exif data try: print(float(Fraction(exif_data['Exif.Photo.FocalLength'])) / 1000) focal_length = float(Fraction(exif_data['Exif.Photo.FocalLength']) ) / 1000 #if present converts focal length to m except KeyError: print(f'Error, focal length not found for {image} setting it to 55mm.' ) #if not sets a standard value focal_length = 0.055 og_mag = 1 / ((distance + rings + focal_length) / (focal_length)) #calculate the starting mag.ratio new_mag = og_mag + (rings / focal_length ) #calculate mag.ratio with macro rings return focal_length, og_mag, new_mag
def writ_gps(image_path, coo): # 转换并写入图像地理范围,存储于Xmp.dc字段下(x1、y1)(x2,y2)下 # {'Xmp.dc.x1': 'E120.25', # 'Xmp.dc.y1': 'N31.05000000000001', # 'Xmp.dc.x2': 'E121.29999999999994', # 'Xmp.dc.y2': 'N30.25'} if coo[0][0] > 0: long_location_lef = "E" else: long_location_lef = "W" if coo[0][1] > 0: lati_location_lef = "N" else: lati_location_lef = "S" if coo[1][0] > 0: long_location_rig = "E" else: long_location_rig = "W" if coo[1][1] > 0: lati_location_rig = "N" else: lati_location_rig = "S" longituade_lef = abs(coo[0][0]) latituade_lef = abs(coo[0][1]) longituade_rig = abs(coo[1][0]) latituade_rig = abs(coo[1][1]) point1_x1 = str(long_location_lef) + str(longituade_lef) + "°" point1_y1 = str(lati_location_lef) + str(latituade_lef) + "°" point2_x1 = str(long_location_rig) + str(longituade_rig) + "°" point2_y2 = str(lati_location_rig) + str(latituade_rig) + "°" img = Image(image_path) img.modify_xmp({"Xmp.dc.x1": point1_x1}) img.modify_xmp({"Xmp.dc.y1": point1_y1}) img.modify_xmp({"Xmp.dc.x2": point2_x1}) img.modify_xmp({"Xmp.dc.y2": point2_y2}) img.close()
def geotag_photo(self, file, lat, lon): img = Image(file) exif_lat = str(int(lat)) + "/1 " + str(int( lat % 1 * 60)) + "/1 " + str( int(round((lat % 1 * 60) % 1 * 60, 4) * 100)) + "/100" exif_lon = str(int(lon)) + "/1 " + str(int( lon % 1 * 60)) + "/1 " + str( int(round((lon % 1 * 60) % 1 * 60, 4) * 100)) + "/100" if int(lat) < 0: exif_lat_ref = 'S' else: exif_lat_ref = 'N' if int(lon) < 0: exif_lon_ref = 'W' else: exif_lon_ref = 'E' img.modify_exif({ 'Exif.GPSInfo.GPSLatitudeRef': exif_lat_ref, 'Exif.GPSInfo.GPSLatitude': exif_lat, 'Exif.GPSInfo.GPSLongitudeRef': exif_lon_ref, 'Exif.GPSInfo.GPSLongitude': exif_lon })
from pyexiv2 import Image img = Image(r'.\pyexiv2\tests\1.jpg') img.read_exif() img.read_iptc() img.read_xmp() img.read_raw_xmp() img.clear_exif() img.read_exif() img.modify_exif({'Exif.Image.Make': 'test-中文-', 'Exif.Image.Rating': ''}) img.read_exif() dict1 = { "Xmp.xmp.CreateDate": "2019-06-23T19:45:17.834", "Xmp.xmp.Rating": "", "Xmp.dc.subject": ["tag1", "tag2", "tag3"] } img.modify_xmp(dict1) img.close() from pyexiv2 import ImageData with open(r'.\pyexiv2\tests\1.jpg', 'rb') as f: with ImageData(f.read()) as img: data = img.read_exif() with open(r'.\pyexiv2\tests\1.jpg', 'rb+') as f: with ImageData(f.read()) as img:
from pyexiv2 import Image img = Image('WechatIMG3.jpeg') data = img.read_exif() data = str(data).replace('.', ' ') with open('1.txt', mode='w', encoding='utf-8') as f: f.write((data)) img.close()
def write_metadata(path, tags): i = Image(path) i.modify_xmp({'Xmp.dc.subject': tags})
def main(): sort = list() for root, directories, filenames in os.walk( sorting_dir): # Create a list of all files in "path" for filename in filenames: f = os.path.join(root, filename) if osp.splitext(f)[1].casefold() not in [".mp4", ".jpg", ".jpeg"]: print(f"Not handling: {f}") continue sort.append(f) print(f"Sorting {len(sort)} file(s)") failed = list() copied = dict() for f in sort: # split the name by _ and extract required information fname = osp.basename(f) ftype = osp.splitext(fname)[1].casefold() print(f"Checking: {fname}") try: # try to get the creation date, else add it to the failed list ## get jpgs and mp4 files only if ftype in [".jpg", ".jpeg"]: fpath = images_dir name_prefix = "IMG" out = probe(f, show_frames=None) try: # try using ffprobe creation_date = out['frames'][0]['tags'][ 'DateTimeOriginal'] except: try: # try using pyexiv 2 img = Image(f) except: # if reading fails, it might still have the information, because it's weird pass creation_date = img.read_exif()["Exif.Image.DateTime"] elif ftype == ".mp4": name_prefix = "VID" fpath = videos_dir out = probe(f) creation_date = out['format']['tags']['creation_time'] else: print("Not handling") continue except: failed.append(f) continue ## get the date parts from the creation_date fyear = creation_date[:4] fmonth = creation_date[5:7] fday = creation_date[8:10] fhour = creation_date[11:13] fminute = creation_date[14:16] fsecond = creation_date[17:19] # create a datetime object from the file name info fdate = datetime(int(fyear), int(fmonth), int(fday), int(fhour), int(fminute), int(fsecond)) new_name = f"{name_prefix}_{fyear}{fmonth}{fday}_{fhour}{fminute}{fsecond}" # this variable will be an empty string if separate_files is False, else it's equal to fpath basename = fpath if separate_filetypes else "" # use a splat operator to join every element of the path_format list pre_formatted_path = osp.join(*path_format) path = osp.join(fdate.strftime(pre_formatted_path), basename) os.makedirs( path, exist_ok=True) # make directories, unless they already exist new_path = osp.join( path, f"{new_name}" ) # the path of the file after being copied without the extension ## check if the file already exists check_name = f"{new_path}{ftype}" if osp.isfile(check_name) and check_name not in copied: print(f"File already exists: {check_name}") continue new_file = copyfile(f, new_path, ftype) print(f"Copyied file: {f} → {new_file}") copied[new_file] = f if not copy_files: # delete old files? os.remove(floc) for f in failed: print(f)
def write_exif(pic_path, exif_data): img = Image(pic_path) img.clear_exif() #这里为防止两套数据冲突清空了已有的原exif img.modify_exif(exif_data) img.close()
entries = os.scandir(path) indexFile = open(path + "\\index.txt", mode="r", encoding="utf-8") os.mkdir(path + "\\to_delete\\") next_date_for_pictures = '' num_photos_with_date = 0 while True: fileName = indexFile.readline().strip() description = indexFile.readline().strip() dateTaken = indexFile.readline().strip() if not dateTaken: break # EOF if description != 'delete': metadata = Image(path + "\\" + fileName) xmp = {'Xmp.dc.description': description} metadata.modify_xmp(xmp) if dateTaken == next_date_for_pictures: # add a second to make the next picture think that it comes next split_date = dateTaken.split(":") minutes = split_date[3] split_date[3] = str(int(minutes) + num_photos_with_date).zfill(2) num_photos_with_date += 1 dateTaken = ":".join(split_date) else: num_photos_with_date = 1 next_date_for_pictures = dateTaken exif = {
from pyexiv2 import Image i = Image('DJI_0294.JPG') Information = i.read_exif() for keys, values in Information.items(): print(keys + ':' + values + '\n') print('*********************') for keys, values in i.read_xmp().items(): print(keys + ':' + values + '\n')
def read_exif(): i = Image("imgs/2.jpg") print(i.read_exif()) print(i.read_iptc()) print(i.read_xmp())
import glob import argparse import io from pyexiv2 import Image if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--pathname", type=str) parser.add_argument("--recursive", action="store_true") args = parser.parse_args() for filename in glob.iglob(args.pathname, recursive=args.recursive): print(filename) img = Image(filename) md = img.read_xmp() img.close() reverse_offset = int(md["Xmp.GCamera.MicroVideoOffset"]) with open(filename, "rb") as f: f.seek(reverse_offset * -1, 2) rest_of_file = f.read() print(f.tell()) with open(filename + ".mp4", "wb") as wf: wf.write(rest_of_file)
img = cv2.imread(file.path) img = get_grayscale(img) #img=thresholding(img) img = dilate(img) d = pytesseract.image_to_data(img, output_type=Output.DICT) for i in range(len(d['text'])): if d['text'][i] == 'GARMIN': find = True day = d['text'][i + 1] hour = d['text'][i + 2] lat = float(d['text'][i + 3]) lon = float(d['text'][i + 4]) img = Image(file.path) exif_lat = str(int(lat)) + "/1 " + str(int( lat % 1 * 60)) + "/1 " + str( int(round((lat % 1 * 60) % 1 * 60, 4) * 100)) + "/100" exif_lon = str(int(lon)) + "/1 " + str(int( lon % 1 * 60)) + "/1 " + str( int(round((lon % 1 * 60) % 1 * 60, 4) * 100)) + "/100" if int(lat) < 0: exif_lat_ref = 'S' else: exif_lat_ref = 'N' if int(lon) < 0: exif_lon_ref = 'W' else: exif_lon_ref = 'E'
import os import sys from pyexiv2 import Image print('Number of arguments:', len(sys.argv), 'arguments.') print('Argument List:', str(sys.argv)) path = sys.argv[1] entries = os.scandir(path) indexFile = open(path + "\\index.txt", mode="w", encoding="utf-8") def get_image_description(path, metadata): if path.endswith('_b.jpg'): return metadata.get('Exif.Image.ImageDescription', 'delete') return metadata.get('Exif.Image.ImageDescription', '') for entry in entries: if entry.name.endswith('.jpg'): i = Image(entry.path) metadata = i.read_exif() photo_date = metadata.get('Exif.Photo.DateTimeOriginal') description = get_image_description(entry.path, metadata) line = entry.name + '\n' + description + '\n' + photo_date print(line) indexFile.write(line + '\n')
def edit_exif(): i = Image("imgs/1.jpg") _dict = {"Exif.Image.Copyright": "津云"} i.modify_exif(_dict)