• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python exifread.process_file函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: render_thumb

def render_thumb(width, imgfile):
	try:
		imgpath=pkg_resources.resource_filename('vishwin_http.views', 'img/' + imgfile)
		thumbfile=width + 'px-' + imgfile
		thumbpath=pkg_resources.resource_filename('vishwin_http.views', 'generated/thumb/' + thumbfile)
		# get file modified time for original; will throw exception if not found
		mtime_orig=os.path.getmtime(imgpath)
		if not (os.path.isfile(thumbpath)) or (os.path.getmtime(thumbpath) < mtime_orig):
			img=open(imgpath, 'rb')
			tags=exifread.process_file(img, details=False, stop_tag='Image_Orientation')
			img.close()
			# reopen using PIL
			img=Image.open(imgpath)
			# upon transpose, format attribute in object is cleared
			format=img.format
			if 'Image Orientation' in tags:
				if tags['Image Orientation'].values[0]>=5:
					# rotations in PIL(low) are anti-clockwise, would be easier if clockwise was default
					img=img.transpose(Image.ROTATE_270)
				if (tags['Image Orientation'].values[0]==(3 or 4)) or tags['Image Orientation'].values[0]>=7:
					img=img.transpose(Image.ROTATE_180)
				# flipped images
				if tags['Image Orientation'].values[0]==(2 or 4 or 5 or 7):
					img=img.transpose(Image.FLIP_LEFT_RIGHT)
			img.thumbnail((int(width), int(width)/(img.size[0]/img.size[1])))
			img.save(thumbpath, format)
			img.close()
		return send_file(thumbpath, mimetype=guess_type(imgpath)[0])
	except OSError:
		abort(404)
开发者ID:vishwin,项目名称:vishwin.info-http,代码行数:30,代码来源:views.py


示例17: populate_exif

def populate_exif(event):
    """ Populate EXIF data and location(if not present).

    Not all EXIF data is stored. GPS coordinates are converted
    to floats.

    Test image with GPS data: http://bit.ly/1VTFA5W
    """
    url = event.fields['url'].new_value
    response = requests.get(url)
    image_file = StringIO(response.content)
    raw_exif = exifread.process_file(image_file, details=False)

    # EXIF data
    exclude = ('Thumbnail', 'Interoperability', 'MakerNote', 'GPS')
    exif_data = {key: val.printable for key, val in raw_exif.items()
                 if key.split()[0] not in exclude}
    event.set_field_value('exif', exif_data)

    # GPS data
    loc_field = event.fields.get('location')
    if not loc_field or not loc_field.new_value:
        gps_data = {key.split()[-1]: val.values
                    for key, val in raw_exif.items()
                    if key.startswith('GPS')}
        lat, lon = get_lat_lon(gps_data)
        event.set_field_value('location', {'lat': lat, 'lon': lon})
开发者ID:ramses-tech,项目名称:ramses-playground,代码行数:27,代码来源:__init__.py


示例18: tags

	def tags(self):
		if self._tags == None:
			if self.file_container != None:
				self._tags = self.file_container.tags
			else:
				self._tags = exifread.process_file(self.handle, details=False)
		return self._tags
开发者ID:XerxesDGreat,项目名称:py_photo_browser,代码行数:7,代码来源:model.py


示例19: read_exif

def read_exif(filename, upload_date, is_image):
    exif = exifread.process_file(open(filename, "rb"))
    timestamp = None
    year, month, day = upload_date.year, upload_date.month, upload_date.day
    exif_read = bool(exif)
    if "EXIF DateTimeOriginal" in exif:
        timestamp = str(exif["EXIF DateTimeOriginal"])
        # fmt='2015:12:04 00:50:53'
        year, month, day = timestamp.split(" ")[0].split(":")
        year, month, day = int(year), int(month), int(day)

    dims = None, None
    if is_image:
        dims = Image.open(filename).size

    brand = str(exif.get("Image Make", "Unknown camera"))
    model = str(exif.get("Image Model", ""))

    return {
        "year": year,
        "month": month,
        "day": day,
        "timestamp": timestamp,
        "camera": "%s %s" % (brand, model),
        "orientation": str(exif.get("Image Orientation", "Horizontal (normal)")),
        "width": dims[0],
        "height": dims[1],
        "size": os.stat(filename).st_size,
        "exif_read": exif_read,
    }
开发者ID:jjdelc,项目名称:Photolog,代码行数:30,代码来源:base.py


示例20: verify_exif

def verify_exif(filename):
    '''
    Check that image file has the required EXIF fields.

    Incompatible files will be ignored server side.
    '''
    # required tags in IFD name convention
    required_exif = ["GPS GPSLongitude", "GPS GPSLatitude", "EXIF DateTimeOriginal", "Image Orientation", "GPS GPSImgDirection"]
    description_tag = "Image ImageDescription"

    with open(filename, 'rb') as f:
        tags = exifread.process_file(f)

    # make sure no Mapillary tags
    if description_tag in tags:
        if "MAPSequenceUUID" in tags[description_tag].values:
            print("File contains Mapillary EXIF tags, use upload.py instead.")
            return False

    # make sure all required tags are there
    for rexif in required_exif:
        if not rexif in tags:
            print("Missing required EXIF tag: {0}".format(rexif))
            return False

    return True
开发者ID:rweait,项目名称:mapillary_tools,代码行数:26,代码来源:upload_with_authentication.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python exifutil.open_oriented_im函数代码示例发布时间:2022-05-24
下一篇:
Python exercise1.pig_latinify函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap