当前位置: 首页>>代码示例>>Python>>正文


Python exifread.process_file函数代码示例

本文整理汇总了Python中exifread.process_file函数的典型用法代码示例。如果您正苦于以下问题:Python process_file函数的具体用法?Python process_file怎么用?Python process_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了process_file函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _metadata_exif

 def _metadata_exif(self, metadata_file_path):
     """Read exif metadata from a jpg or tiff file using exifread."""
     # TODO: can we shorten this method somehow?
     with open(self.src_path, 'rb') as img:
         tags = None
         try:
             tags = exifread.process_file(img, debug=True)
         except Exception as e:
             self.add_error(e, "Error while trying to grab full metadata for file {}; retrying for partial data.".format(self.src_path))
         if tags is None:
             try:
                 tags = exifread.process_file(img, debug=True)
             except Exception as e:
                 self.add_error(e, "Failed to get any metadata for file {}.".format(self.src_path))
                 return False
         for tag in sorted(tags.keys()):
             # These tags are long and obnoxious/binary so we don't add them
             if tag not in ('JPEGThumbnail', 'TIFFThumbnail'):
                 tag_string = str(tags[tag])
                 # Exifreader truncates data.
                 if len(tag_string) > 25 and tag_string.endswith(", ... ]"):
                     tag_value = tags[tag].values
                     tag_string = str(tag_value)
                 with open(metadata_file_path, 'w+') as metadata_file:
                     metadata_file.write("Key: {}\tValue: {}\n".format(tag, tag_string))
         # TODO: how do we want to log metadata?
         self.set_property('metadata', 'exif')
     return True
开发者ID:CIRCL,项目名称:PyCIRCLean,代码行数:28,代码来源:filecheck.py

示例2: _metadata_exif

    def _metadata_exif(self, metadataFile):
        img = open(self.cur_file.src_path, 'rb')
        tags = None

        try:
            tags = exifread.process_file(img, debug=True)
        except Exception as e:
            print("Error while trying to grab full metadata for file {}; retrying for partial data.".format(self.cur_file.src_path))
            print(e)
        if tags is None:
            try:
                tags = exifread.process_file(img, debug=True)
            except Exception as e:
                print("Failed to get any metadata for file {}.".format(self.cur_file.src_path))
                print(e)
                img.close()
                return False

        for tag in sorted(tags.keys()):
            # These are long and obnoxious/binary
            if tag not in ('JPEGThumbnail', 'TIFFThumbnail'):
                printable = str(tags[tag])

                # Exifreader truncates data.
                if len(printable) > 25 and printable.endswith(", ... ]"):
                    value = tags[tag].values
                    if isinstance(value, basestring):
                        printable = value
                    else:
                        printable = str(value)
                metadataFile.write("Key: {}\tValue: {}\n".format(tag, printable))
        self.cur_file.add_log_details('metadata', 'exif')
        img.close()
        return True
开发者ID:Rafiot,项目名称:PyCIRCLean,代码行数:34,代码来源:filecheck.py

示例3: analyze_pictures

def analyze_pictures(src_folder, dest_folder, pictures):
    prevpic = None
    curpath = None
    curtags = None
    filedic = {}
    cr2s = []
    curpanorama = []
    count = 0
    date_of_previous_panorama = None

    for pic in pictures:
        print(pic)
        if os.path.splitext(pic)[1].lower() == ".cr2":
            cr2s.append(pic)
        if os.path.splitext(pic)[1].lower() in ['.jpg', '.jpeg', '.png', '.mov']:
            # Get File and ExifTags
            curpath = src_folder + pic
            with open(curpath, 'rb') as cf:
                curtags = exifread.process_file(cf, details=False)
            # Calculate Subfolder
            filedic[pic] = get_folder(dest_folder,
                                      get_date(curpath, curtags).isoformat())
            if prevpic is not None:
                prevpath = src_folder + prevpic
                with open(prevpath, 'rb') as pf:
                    prevtags = exifread.process_file(pf, details=False)

                if fulfill_panorama_criterias(prevpath, curpath, prevtags, curtags):
                    if len(curpanorama) == 0:
                        curpanorama.append(prevpic)
                    curpanorama.append(pic)

                elif len(curpanorama) > 0:
                    # Just finished a panorama
                    if date_of_previous_panorama and not date_of_previous_panorama == get_date(prevpath, prevtags):
                        count = 0

                    count += 1
                    for x in curpanorama:
                        filedic[x] = filedic[x] + "Panorama " + str(count) + "/"

                    curpanorama = []
                    date_of_previous_panorama = get_date(prevpath, prevtags)
            prevpic = pic

    # If last picture was part of panorama
    if len(curpanorama) > 0:
        if not date_of_previous_panorama == get_date(curpath, curtags):
            count = 0
        count += 1
        for x in curpanorama:
            filedic[x] = filedic[x] + "Panorama " + str(count) + "/"

    # There has to be a JPG for each CR2 (-> RAW+L ; only RAW not supported yet)
    for x in cr2s:
        tmp = x.rsplit('.', 1)[0] + '.JPG'
        filedic[x] = filedic[tmp]

    return filedic
开发者ID:maust,项目名称:image-sorter,代码行数:59,代码来源:sorter.py

示例4: test_NotfulfillPanoramaCriterias1

 def test_NotfulfillPanoramaCriterias1(self):
     path1 = 'test_files/P1010003.JPG'
     pic1 = open(path1, 'rb')
     pic1_tags = exifread.process_file(pic1, details=False)
     path2 = 'test_files/P1010004.JPG'
     pic2 = open(path2, 'rb')
     pic2_tags = exifread.process_file(pic2, details=False)
     case = sorter.fulfill_panorama_criterias(path1, path2, pic1_tags, pic2_tags)
开发者ID:maust,项目名称:image-sorter,代码行数:8,代码来源:sorter_test.py

示例5: EXIF

 def EXIF(self, file=None):
     try:
         if file:
             tags = exifread.process_file(file)
         else:
             with self.image.storage.open(self.image.name, 'rb') as file:
                 tags = exifread.process_file(file, details=False)
         return tags
     except:
         return {}
开发者ID:buggady,项目名称:texasfyre2,代码行数:10,代码来源:models.py

示例6: test_fulfillPanoramaCriterias1

 def test_fulfillPanoramaCriterias1(self):
     path1 = 'test_files/IMG_5627.JPG'
     pic1 = open(path1, 'rb')
     pic1_tags = exifread.process_file(pic1, details=False)
     path2 = 'test_files/IMG_5628.JPG'
     pic2 = open(path2, 'rb')
     pic2_tags = exifread.process_file(pic2, details=False)
     case = sorter.fulfill_panorama_criterias(path1, path2, pic1_tags, pic2_tags)
     self.assertTrue(case)
开发者ID:maust,项目名称:image-sorter,代码行数:9,代码来源:sorter_test.py

示例7: __init__

 def __init__(self, filename, details=False):
     '''
     Initialize EXIF object with FILE as filename or fileobj
     '''
     self.filename = filename
     if type(filename)==str:
         with open(filename, 'rb') as fileobj:
             self.tags = exifread.process_file(fileobj, details=details)
     else:
         self.tags = exifread.process_file(filename, details=details)
开发者ID:elopio,项目名称:mapillary_tools,代码行数:10,代码来源:exif.py

示例8: compare

def compare(*args):
    """"define your compare method here"""
    f1 = open(path_name1, 'rb')
    tags1 = exifread.process_file(f1)  #stores EXIF data of first image file

    f2 = open(path_name2, 'rb')
    tags2 = exifread.process_file(f2)  #stores EXIF data of second image file
    if tags1 == tags2:
        print "Stop!,%s and %s are similar"%(y[j],y[k])
    else:
        print(" No similar Images found ")
开发者ID:mysticTot,项目名称:Digital_Image_copy_checker,代码行数:11,代码来源:exif_data_compare.py

示例9: print_image_tags

def print_image_tags(file):
    from exifread import process_file

    tags = process_file(open(file), strict=True)

    for tag in tags.keys():
        print "Key: %s, value %s" % (tag, tags[tag])
开发者ID:duncanwp,项目名称:PyPic,代码行数:7,代码来源:utils.py

示例10: extract_metadata

def extract_metadata(file):
    # load the EXIF data
    file.seek(0)
    tags = exifread.process_file(file, details=False)
    print tags

    # title
    name = None
    if "Image ImageDescription" in tags:
        name = tags['Image ImageDescription'].values
    else:
        name = secure_filename(file.filename)

    # GPS coordinates
    longitude = get_coordinate('GPS GPSLongitude', 'GPS GPSLongitudeRef', tags)
    latitude = get_coordinate('GPS GPSLatitude', 'GPS GPSLatitudeRef', tags)
    altitude = compute_single_ratio(tags['GPS GPSAltitude'].values[0]) \
        if 'GPS GPSAltitude' in tags else None

    metadata = {"name": name,
                "latitude": latitude,
                "longitude": longitude,
                "altitude": altitude}

    return metadata
开发者ID:bezineb5,项目名称:ImageMatcher,代码行数:25,代码来源:metadata_extraction.py

示例11: get_exif

def get_exif(picture):
    """
    :param picture: Is the image file user selects. Extract EXIF data.
    :return:
    """
    image = open(picture, 'rb')
    tags = exifread.process_file(image)
    gps_out = []
    what_i_need = ('GPS GPSLatitude', 'GPS GPSLatitudeRef', 'GPS GPSLongitude', 'GPS GPSLongitudeRef')
    for tag in what_i_need:
        try:
            val = "%s" % tags[tag]
            if isinstance(val, list):
                gps_out.extend(map(str, float(val)))
            else:
                gps_out.append(val)
        except KeyError:
            print('Key %s does not exists' % tag)

    # Had a list of strings and had to do following code so they wouldn't break when I calculated them.
    list1 = gps_out[0]
    list2 = gps_out[2]
    latitude = list1.strip("[]").split(",")
    longitude = list2.strip("[]").split(",")
    last_number_lat = latitude[2].split("/")
    last_number_long = longitude[2].split("/")
    latitude[2] = int(last_number_lat[0]) / int(last_number_lat[1])
    longitude[2] = int(last_number_long[0]) / int(last_number_long[1])
    latlong_to_degress(latitude, longitude)
开发者ID:Jaren831,项目名称:usafa,代码行数:29,代码来源:Lab04.py

示例12: get_new_image_name_translations

def get_new_image_name_translations(indir, outdir):
    """ Renames input images using timestamp of
        EXIF's DateTimeOriginal tag. """
    origpaths = glob.glob("%s/*.[jJ][pP][gG]" % indir)
    d = {}
    for p in origpaths:
        try:
            f = open(p)
            exif = exifread.process_file(f)
        except:
            raise
        finally:
            f.close()
        try:
            orientation = str(exif["Image Orientation"])
        except KeyError:
            orientation = None

        try:
            origtime = str(exif["EXIF DateTimeOriginal"])
            time_extracted = True
        except KeyError:
            print("No exif data!")
            time_extracted = False
        if time_extracted:
            ts = int(time.mktime(datetime.datetime.strptime(origtime, "%Y:%m:%d %H:%M:%S").timetuple()))
        else:
            ts = int(time.time())
        newpath = os.path.join(outdir, str(ts) + ".jpg")
        d[p] = {"newpath": newpath, "orientation": orientation }
    return d
开发者ID:kahunacohen,项目名称:ias,代码行数:31,代码来源:process-images.py

示例13: extract_and_attach_metadata

def extract_and_attach_metadata(mediaitem, filepath):
    if mediaitem.media_type_cd == 100:
        try:
            media_file = open(filepath, 'rb')
            tags = exifread.process_file(media_file, details=False)
            org_date_tag = tags.get('EXIF DateTimeOriginal')
            org_date = datetime.now()
            if org_date_tag:
                org_date = datetime.strptime(str(org_date_tag), '%Y:%m:%d %H:%M:%S')
            else:
                org_date_tag = tags.get('EXIF DateTimeDigitized')
                if org_date_tag:
                    org_date = datetime.strptime(str(org_date_tag), '%Y:%m:%d %H:%M:%S')
                else:
                    org_date_tag = os.stat(filepath).st_birthtime
                    if org_date_tag:
                        org_date = datetime.fromtimestamp(org_date_tag)
                    else:
                        org_date_tag = os.stat(filepath).st_ctime
                        if org_date_tag:
                            org_date = datetime.fromtimestamp(org_date_tag)
            mediaitem.origin_date = org_date
        except:
            logging.error('failed to extract metadata for: ' + str(mediaitem))
    file_size = os.stat(filepath).st_size

    mediaitem.file_size = file_size
    logging.log(logging.DEBUG, str(mediaitem) + ' - set file size = ' + str(file_size))
开发者ID:mangosmoothie,项目名称:picappa,代码行数:28,代码来源:syncservices.py

示例14: getEXIFTime

def getEXIFTime(fileName):
    # get the image time based on EXIF metadata, esle use mod time
    newName = ""
    f = open(fileName,'rb')
    try:
        # tags = exifread.process_file(f)
        tags = exifread.process_file(f, stop_tag='EXIF DateTimeOriginal', details=False)
        # tags = exifread.process_file(f,stop_tag='EXIF DateTime')
        # print(tags['EXIF DateTimeOriginal'])
    except:
        # the error will be caught in the tag processing
        pass

    try:
        # get the exif version date time
        EXIFDateTime = str(tags['EXIF DateTimeOriginal'])
        # print("EXIFDateTime ="+EXIFDateTime)
        #exclude filetype
        newName = EXIFDateTime.replace(':','-') #+"."+fileName[-3:]
    except:
        # else use the file modified date (Creation gets changed on copy)
        print ("Couldn't read EXIF date on " + fileName + "\nUsing mod time")
        # exclude filetype
        newName = getModTime(fileName) # + "."+fileName[-3:]

    f.close()

    return newName
开发者ID:ghillebrand,项目名称:PhotoTransfer,代码行数:28,代码来源:RenameStills.py

示例15: get_resolution

def get_resolution(image, camera):
    """Return various resolution numbers for an image."""
    try:
        if "raw" in camera.image_types and os.path.splitext(image)[-1].lower().strip(".") in RAW_FORMATS:
            with open(image, "rb") as fh:
                exif_tags = exifread.process_file(
                    fh, details=False)
            try:
                width = exif_tags["Image ImageWidth"].values[0]
                height = exif_tags["Image ImageLength"].values[0]
                if ("rotated 90" in str(exif_tags["Image Orientation"]).lower()):
                    temp = height
                    height = width
                    width = temp
                image_resolution = (width, height)
            except KeyError:
                image_resolution = (0, 0)
        else:
            try:
                image_resolution = Image.open(image).size
            except ValueError:
                print("Value Error?")
                image_resolution = (0, 0)
    except IOError:
        image_resolution = (0, 0)
    folder, res = "originals", 'fullres'
    return res, image_resolution, folder
开发者ID:borevitzlab,项目名称:exif2timestream,代码行数:27,代码来源:exif2timestream.py


注:本文中的exifread.process_file函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。