示例#1
0
def rotate_upright(img):
   ret = {}
   info =  img._getexif()
   for tag, value in info.items():
      decoded = TAGS.get(tag, tag)
      if decoded == "Orientation": 
         orientation = value
         #print "before:" + str(value)
   if orientation is 6: img = img.rotate(-90)
   elif orientation is 8:
      img = img.rotate(90)
      print type(img)
      print orientation
   elif orientation is 3: img = img.rotate(180)
   elif orientation is 2: img = img.transpose(Image.FLIP_LEFT_RIGHT)
   elif orientation is 5: img = img.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT)
   elif orientation is 7: img = img.rotate(90).transpose(Image.FLIP_LEFT_RIGHT)
   elif orientation is 4: img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
   print type(img)
   ret = {}
   info =  img._getexif()
   for tag, value in info.items():
      decoded = TAGS.get(tag, tag)
      if decoded == "Orientation": 
         orientation = value
         print "before:" + str(value)
   return img
示例#2
0
  def attributes(self, node):
    attr = VMap()
    vfile = node.open()
    img = Image.open(vfile) 
    info = img._getexif()
    vfile.close()
    for tag, values in info.items():
      if tag in self.dateTimeTags:
       try:
	decoded = str(TAGS.get(tag, tag))
 	try:
	  dt = strptime(values, "%Y:%m:%d %H:%M:%S") 
        except ValueError:
	  try:
	    dt = strptime(values[:-6], "%Y-%m-%dT%H:%M:%S")
	  except ValueError:
	    dt = strptime(values.rstrip(' '),  "%a %b %d %H:%M:%S")
	vt = vtime(dt.tm_year, dt.tm_mon, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec, 0)
        vt.thisown = False
	attr[decoded] = Variant(vt) 	
       except Exception as e:
	attr[decoded] = Variant(str(values))
      else:	
        decoded = str(TAGS.get(tag, tag))
        if isinstance(values, tuple):
	  vl = VList()
	  for value in values:
	     vl.push_back(Variant(value))
          attr[decoded] = vl
        else:
          attr[decoded] = Variant(values)
    return attr
示例#3
0
文件: utils.py 项目: mnbundle/bushlog
def get_exif_data(image_path, exif_include_keys=EXIF_INCLUDE_KEYS):
    """
    Returns all the image's exif data as a dict.
    """
    image_file = pil.open(image_path)
    try:
        raw_exif_data = image_file._getexif()
    except AttributeError:
        raw_exif_data = None

    if not raw_exif_data:
        return None

    exif_data = {}
    for key, value in raw_exif_data.items():
        decoded_key = TAGS.get(key, key)
        if decoded_key in exif_include_keys:
            if decoded_key == "DateTimeOriginal":
                try:
                    value = datetime.strptime(value, "%Y:%m:%d %H:%M:%S")
                except ValueError:
                    value = datetime.now()
            exif_data[decoded_key] = value

    return exif_data

    [{TAGS.get(key, key): value}for key, value in raw_exif_data.items()]
def get_exif(file,field):
    img = Image.open(file)
    exif = img._getexif()

    exif_data = []
    for id, value in exif.items():
        if TAGS.get(id) == field:
            tag = TAGS.get(id, id),value
            exif_data.extend(tag)

    return exif_data
示例#5
0
    def __init__(self, imageName, crs):
        QDialog.__init__(self)
        self.ui_exif_info = Ui_Exif2()
        self.ui_exif_info.setupUi(self)
        self.FocalLength = None
        img = Image.open(imageName)
        if hasattr(img,'_getexif'):
            raw = img._getexif()
        else:
            QMessageBox.warning(QMainWindow(),"Error","Image has no EXIF")
            return
        
        sizePicture = img.size
        self.diag = sqrt(sizePicture[0]**2+sizePicture[1]**2)
        if raw != None and any(raw):
            dict = None
            for (k,v) in raw.iteritems():
                if TAGS.get(k) == 'GPSInfo':
                    dict = v
                if TAGS.get(k) == 'FocalLength':
                    self.FocalLength = v
            text = ''
            if dict != None:
                Nord = dict[2][0][0]+dict[2][1][0]/float(dict[2][1][1])/60.0
                Est = dict[4][0][0]+dict[4][1][0]/float(dict[4][1][1])/60.0
                crsTarget = QgsCoordinateReferenceSystem(crs.postgisSrid())
                crsSource = QgsCoordinateReferenceSystem(4326)
                xform = QgsCoordinateTransform(crsSource, crsTarget)
                LocalPos = xform.transform(QgsPoint(Est,Nord))
                text += 'Nord: ' + str(LocalPos[0])
                text += '\nEst: ' +str(LocalPos[1])
                text += '\n\n'
 
            text += '============================\n'
            text += 'Raw EXIF data:'
            for (k,v) in raw.iteritems():
                test = True
                if isinstance(v, (int, long, float, complex, bool)):
                    text += "\n  " + str(TAGS.get(k)) + ": " + str(v)
                else:
                    for c in str(v):
                        if isinstance(c, str) and c not in string.ascii_letters and c not in string.digits and c not in string.whitespace and c not in('.',',','(',')',':'):
                            test = False
                    if test:
                        text += "\n  " + str(TAGS.get(k)) + ": " + str(v)

            self.ui_exif_info.textBrowser.setText(text)
        else:
            raise IOError
        
        self.ui_exif_info.pushButton.clicked.connect(self.getFocal)
示例#6
0
def get_exif_data(filename):
    fileinfo = {}
    try:
        img = Image.open(filename)
        if hasattr( img, '_getexif' ):
            exifinfo = img._getexif()
            print exifinfo
            if exifinfo != None:
                fileinfo = dict([(TAGS.get(key,key), str(value).decode('utf-8', 'ignore'))
                        for key, value in exifinfo.items()
                        if type(TAGS.get(key,key)) is str])
    except IOError:
        logging.error(filename)
    return fileinfo
示例#7
0
def get_exif(file):
  img = Image.open(file)
  df=np.array(Image.open(file))
  exif = img._getexif()

  exif_data = []
  for id, value in exif.items():
    #print 'ID',TAGS.get(id),'\n'
    ID = TAGS.get(id)
    tag = TAGS.get(id, id),value
    #print 'Tag',tag,'\n'
    if ID == 'GPSInfo': 
      exif_data.extend(tag)
  return exif_data
示例#8
0
def get_exif_data(fname):
	"""Get embedded EXIF data from image file."""
	fileinfo = {}
	try:
		img = Image.open(fname)
		if hasattr( img, '_getexif' ):
			exifinfo = img._getexif()
			print exifinfo
			if exifinfo != None:
				fileinfo = dict([(TAGS.get(key,key),value)
					for key, value in exifinfo.items()
						if type(TAGS.get(key,key)) is str])
	except IOError:
		logging.error(fname)
	return fileinfo
示例#9
0
def _get_exifgps(i):
    ret = {}

    info = i._getexif()

    if info:
        for tag, values in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                lat, lon, altitude, gps_data = _extract_gpsinfo(values)
        # try:
        #     iptc = IptcImagePlugin.getiptcinfo(i)
        #     ret['caption'] = iptc[(2,120)]
        #     ret['copyright'] = iptc[(2,116)]
        #     ret['keywords'] = iptc[(2,25)]
        # except:
        #     ret['headline'] = None
        #     ret['caption'] = None
        #     ret['copyright'] = None
        #     ret['keywords'] = []

    ret['latitude'] = lat
    ret['longitude'] = lon
    ret['altitude'] = altitude
    ret[decoded] = gps_data

    return ret
def testForExif(imgFileName):

	try:
		
		print "[+] Testing for exif Metadata"
		exifData = {}
		imgFile = Image.open(imgFileName)
		info = imgFile._getexif()
		if info:
			for (tag, value) in info.items():

				decoded = TAGS.get(tag, tag)
				exifData[decoded] = value
			
			exifGPS = exifData['GPSInfo']
				
			if exifGPS:
				print '[*] ' + str(imgFileName) + ' contains GPS MetaData'
			else:
				print '[-] NO GPS data found'
		else:
				print '[-] NO  data found'



	except Exception, e:
		print "[-] Error : " + str(e)
示例#11
0
文件: image.py 项目: IFGHou/golismero
    def get_exif(self):
        """
        Get EXIF tags for JPEG images. Fails for non-JPEG images.

        :returns: EXIF tags.
        :rtype: dict(str -> str)

        :raise ValueError: Not a JPEG image.
        """

        # Check that it's really an image.
        if self.mime_subtype != "jpeg":
            raise ValueError("Not a JPEG image")

        # Lazy import.
        global PIL_TAGS
        if PIL_TAGS is None:
            from PIL.ExifTags import TAGS as PIL_TAGS

        # Load in PIL.
        img = self.to_pil()

        # Extract the EXIF tags.
        exif = {}
        try:
            info = img.tag.tags
        except AttributeError:
            info = img._getexif()
        if info:
            for tag, value in info.items():
                decoded = PIL_TAGS.get(tag, tag)
                exif[decoded] = value

        # Return the EXIF tags.
        return exif
def show_geodata_for_image(imageSrc, imageFilePath):
	"""
	Searches for GPS data in the image and shows it if found and valid.
	"""
	exitData = {}
	try:
		imageFile = Image.open(imageFilePath)
		info = imageFile._getexif()
	except:
		return

	if info:
		for (tag, value) in info.items():
			decoded = TAGS.get(tag, tag)
			if decoded == 'GPSInfo':
				gpsData = {}
				for t in value:
					decodedGps = GPSTAGS.get(t, t)
					gpsData[decodedGps] = value[t]

				if 'GPSLatitude' in gpsData and 'GPSLatitudeRef' in gpsData and 'GPSLongitude' in gpsData and 'GPSLongitudeRef' in gpsData:
					latitude = convert_to_degrees(gpsData['GPSLatitude'])
					if gpsData['GPSLatitudeRef'] != 'N':
						latitude = 0 - latitude
					longitude = convert_to_degrees(gpsData['GPSLongitude'])
					if gpsData['GPSLongitude'] != 'E':
						longitude = 0 - longitude
					if latitude !=0 and longitude != 0:
						print 'GPS data for %s: latitude=%f%s, longitude=%f%s' % (imageSrc, latitude, gpsData['GPSLatitudeRef'], longitude, gpsData['GPSLongitudeRef'])

				break
示例#13
0
    def extract(self, filepath):
        fd = Image.open(filepath)
        exif = fd._getexif() # raw exif
        gps = {} # raw undecoded gps
        results = {} 

        if exif:
            for (k, v) in exif.items():
                results[TAGS.get(k, k)] = v

        if exif and ExifExtract.GPSINFO in exif:
            for t in exif[ExifExtract.GPSINFO]:
                sub_decoded = GPSTAGS.get(t, t)
                gps[sub_decoded] = exif[ExifExtract.GPSINFO][t]

        if 'GPSLatitude' in gps and 'GPSLatitudeRef' in gps and 'GPSLongitude' in gps and 'GPSLongitudeRef' in gps:
            lat_deg = self._to_degrees(gps['GPSLatitude'])
            if 'N' is not gps['GPSLatitudeRef']:
                lat_deg *= -1

            lng_deg = self._to_degrees(gps['GPSLongitude'])
            if 'E' is not gps['GPSLongitudeRef']:
                lng_deg *= -1

            results['GPS'] = {
                'longitude': lng_deg,
                'latitude': lat_deg
            }

        return results
示例#14
0
def rotate(img):
    try:
        exif = img._getexif()
    except:
        return img

    if not exif or not exif.items:
        return img

    for tag, value in exif.items():
        decoded = TAGS.get(tag, tag)
        if decoded == 'Orientation':
            if value == 1:
                return img
            elif value == 2:
                return img.transpose(Image.FLIP_LEFT_RIGHT)
            elif value == 3:
                return img.transpose(Image.ROTATE_180)
            elif value == 4:
                return img.transpose(Image.FLIP_TOP_BOTTOM)
            elif value == 5:
                return img.transpose(Image.ROTATE_90).transpose(Image.FLIP_LEFT_RIGHT)
            elif value == 6:
                return img.transpose(Image.ROTATE_270)
            elif value == 7:
                return img.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)
            elif value == 8:
                return img.transpose(Image.ROTATE_90)
            else:
                return img

    return img
示例#15
0
def getExif(filename):
    """Returns EXIF data from a file -- currently, creation date and orientation
    Args:
        filename"""
    exif = {}
    i = Image.open(filename)
    info = i._getexif()
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            exif[decoded] = value
        try:
            exif['DateTimeOriginal']
            dtime = exif['DateTimeOriginal']
        except KeyError:
            print "Caution: No EXIF datetime data"
            dtime = None
        except:
            #Any other error
            print "Error in reading EXIF date stamp"
            dtime = None
        try: 
            exif['Orientation']
            orient = exif['Orientation']
        except KeyError:
            print "Caution: No EXIF orientation data"
            orient = 1
        except:
            #Any other error
            print "Error in reading EXIF orientation information"
            orient = 1
        return dtime, orient
    else: 
        return None, None
示例#16
0
文件: get_exif.py 项目: mitshel/HM
    def handle(self, *args, **options):
        for photo_id in options['photo_id']:
            try:
                img=PhotoImages.objects.get(id=photo_id)
            except PhotoAlbums.DoesNotExist:
                self.stdout.write('Not find PhotoImage for ID:"%s"'%photo_id)
            else:
                self.stdout.write('Get EXIF data (%s) for photo( album:%s, path:%s, filename:%s)'%(options['tags'],img.album.tag, img.path, img.filename))
                full_path=os.path.join(img.album.base_path, img.path, img.filename)
                if os.path.exists(full_path):
                    photo=Image.open(full_path)

                    # Получаем Exif
                    try:
                        exif = photo._getexif()
                    except:
                        exif = None
                        self.stdout.write('Error getting EXIF Data')

                    if exif != None:
                        for tag, value in exif.items():
                            decoded = TAGS.get(tag, tag)
                            if options['taglist']:
                                self.stdout.write('%s'%decoded)
                            else:
                                if isinstance(decoded,str):
                                    if ('all' in options['tags']) or (decoded.lower() in options['tags']) or (decoded in options['tags']):
                                        self.stdout.write('%s = %s'%(decoded,value))
                else:
                    self.stdout.write('Image file not found!')
示例#17
0
文件: image.py 项目: Ev4ngelos/sigal
def get_exif_data(filename):
    """Return a dict with the raw EXIF data."""

    logger = logging.getLogger(__name__)

    if PIL.PILLOW_VERSION == '3.0.0':
        warnings.warn('Pillow 3.0.0 is broken with EXIF data, consider using '
                      'another version if you want to use EXIF data.')

    img = PILImage.open(filename)
    try:
        exif = img._getexif() or {}
    except ZeroDivisionError:
        logger.warning('Failed to read EXIF data.')
        return None

    data = {TAGS.get(tag, tag): value for tag, value in exif.items()}

    if 'GPSInfo' in data:
        try:
            data['GPSInfo'] = {GPSTAGS.get(tag, tag): value
                               for tag, value in data['GPSInfo'].items()}
        except AttributeError:
            logger = logging.getLogger(__name__)
            logger.info('Failed to get GPS Info')
            del data['GPSInfo']
    return data
示例#18
0
def remove_exif_orientation(file_path):
    ext = os.path.splitext(file_path)[1].lower()
    if ext == '.jpg' or ext == '.jpeg':
        img = Image.open(file_path)
        exif = img._getexif()
        if not exif:
            return
        orientation = 1
        for (k, v) in exif.items():
            if TAGS.get(k) == 'Orientation':
                orientation = v
        if orientation is 6:
            img = img.rotate(-90)
        elif orientation is 8:
            img = img.rotate(90)
        elif orientation is 3:
            img = img.rotate(180)
        elif orientation is 2:
            img = img.transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation is 5:
            img = img.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation is 7:
            img = img.rotate(90).transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation is 4:
            img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
        img.save(file_path)
示例#19
0
def testForExif(imgFileName):

	try:
		
		exifData = {}
		imgFile = Image.open(imgFileName)
		info = imgFile._getexif()

		if info:
			
			for (tag,value) in info.items():
				decoded = TAGS.get(tag,tag)
				exifData[decoded] = value
			
			exifGPS = exifData["GPSInfo"]

			if exifGPS:
				print("[*] {0} contains GPS MetaData".format(imgFileName))
				return exifGPS
			else:
				return None
	
	except Exception,e:
		print("ERROR: ",e)
		
		return None
示例#20
0
 def __call__(self, data, **metadata):
     try:
         img = Image.open(cStringIO.StringIO(data))
     except IOError:
         return None
     parts = [
         ("Format", str(img.format_description)),
         ("Size", "%s x %s px" % img.size),
         ("Mode", str(img.mode)),
     ]
     for i in sorted(img.info.keys()):
         if i != "exif":
             parts.append(
                 (str(i), str(img.info[i]))
             )
     if hasattr(img, "_getexif"):
         ex = img._getexif()
         if ex:
             for i in sorted(ex.keys()):
                 tag = TAGS.get(i, i)
                 parts.append(
                     (str(tag), str(ex[i]))
                 )
     fmt = format_dict(ODict(parts))
     return "%s image" % img.format, fmt
示例#21
0
def get_exif_header(image):
   """Returns a dictionary from the exif header of an PIL Image. Also converts the GPS Tags.

   Args:
      image: 
   """
   try:
      info = image._getexif()
   except:
      raise gserror.EmptyExifHeaderError('could not found the exif header')
   
   if not info:
      raise gserror.EmptyExifHeaderError('empty exif header')
   
   exif_header = {}   
   for tag, value in info.items():
      tag_id = TAGS.get(tag, tag)
      if tag_id == __EXIF_GPS_INFO:
         gps_info = {}
         for t in value:
            gps_tag_id = GPSTAGS.get(t, t)
            gps_info[gps_tag_id] = value[t]
         exif_header[tag_id] = gps_info
      else:
         exif_header[tag_id] = value
   return exif_header
示例#22
0
 def __call__(self, hdrs, content, limit):
     try:
         img = Image.open(cStringIO.StringIO(content))
     except IOError:
         return None
     parts = [
         ("Format", str(img.format_description)),
         ("Size", "%s x %s px"%img.size),
         ("Mode", str(img.mode)),
     ]
     for i in sorted(img.info.keys()):
         if i != "exif":
             parts.append(
                 (str(i), str(img.info[i]))
             )
     if hasattr(img, "_getexif"):
         ex = img._getexif()
         if ex:
             for i in sorted(ex.keys()):
                 tag = TAGS.get(i, i)
                 parts.append(
                     (str(tag), str(ex[i]))
                 )
     clean = []
     for i in parts:
         clean.append([utils.cleanBin(i[0]), utils.cleanBin(i[1])])
     fmt = common.format_keyvals(
             clean,
             key = "header",
             val = "text"
         )
     return "%s image"%img.format, fmt
示例#23
0
def printExif(image):
    exifAttrs = set(["Model", "Make", "ExifImageWidth", "ExifImageHeight", "FocalLength"])
    exif = {}
    info = image._getexif()
    if info:
        for attr, value in info.items():
            decodedAttr = TAGS.get(attr, attr)
            if decodedAttr in exifAttrs: exif[decodedAttr] = value
    if 'FocalLength' in exif: exif['FocalLength'] = float(exif['FocalLength'][0])/float(exif['FocalLength'][1])

    outputString = ""
    if ('Make' in exif):
        outputString += exif['Make']
    outputString += ","

    if ('Model' in exif):
        outputString += exif['Model']
    outputString += ","

    if ('FocalLength' in exif):
        outputString += str(exif['FocalLength'])
    outputString += ","

    outputString += str(exif['ExifImageWidth']) + "," + str(exif['ExifImageHeight'])

    print(outputString)
示例#24
0
	def get_tiff_tags(self):
		tifftags = self.image.tag.tags
		decoded = {}
		for a, b in tifftags.items():
			val = TAGS.get(a,b)
			decoded[val] = b
		return decoded
示例#25
0
    def _get_exif_data(self, image):
        """Returns a dictionary from the exif data of an PIL Image item.
        Also converts the GPS Tags"""

        exif_data = {}
        try:
            info = image._getexif()
        except AttributeError:
            return exif_data
        except IndexError:
            return exif_data
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value

        return exif_data
示例#26
0
def get_exif(i):
    ret = {}
    info = i._getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        ret[decoded] = value
    return ret
示例#27
0
文件: exif.py 项目: tylertreat/Kanna
def get_exif_data(image):
    """Return a dict from the exif data of a PIL Image and convert the GPS
    tags.
    """

    exif_data = {}
    info = image._getexif()

    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)

            if decoded == "GPSInfo":
                gps_data = {}

                for gps_tag in value:
                    sub_decoded = GPSTAGS.get(gps_tag, gps_tag)
                    gps_data[sub_decoded] = value[gps_tag]

                exif_data[decoded] = gps_data

            else:
                exif_data[decoded] = value

    return exif_data
示例#28
0
def ImageToPixmap(fn):
    try:
        im = Image.open(fn)
    except:
        return None
    exif = {}
    try:
        info = im._getexif()
    except:
        info = None
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            exif[decoded] = value
    date = ''
    if 'DateTimeOriginal' in exif:
        # Date example: 2011:02:26 16:29:49
        try:
            date2 = exif['DateTimeOriginal']
            t = time.strptime(date2,"%Y:%m:%d %H:%M:%S")
            date = time2str(t)
        except:
            pass
    if 'Orientation' in exif:
        if exif['Orientation'] == 6:
            im = im.rotate(-90)
        elif exif['Orientation'] == 3:
            im = im.rotate(180)
        elif exif['Orientation'] == 8:
            im = im.rotate(90)
    data = im.convert('RGBA').tostring('raw', 'BGRA')
    image = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_ARGB32)
    w,h = im.size
    size = str(w) + 'x' + str(h)
    return ((data, QtGui.QPixmap(image)), date+'  '+size)
示例#29
0
def get_GPS(file):
    """
    指定した画像のEXIFデータからGPS_infoを取り出す
    lat: 緯度 -90<=lat<=90, float, 小数点以下6桁
    lon: 経度 -180<=lon<=180, float, 小数点以下6桁
    """
    im = Image.open(file)

    # Exif データを取得
    # 存在しなければそのまま終了 空の辞書を返す
    try:
        exif = im._getexif()
    except AttributeError:
        return {}

    # タグIDそのままでは人が読めないのでデコードして、テーブルに格納する
    exif_table = {}
    for tag_id, value in exif.items():
        tag = TAGS.get(tag_id, tag_id)
        exif_table[tag] = value

    # 緯度latの読み取り。Nを正、Sを負として処理する。
    lat_dir = exif_table['GPSInfo'][1]
    lat = exif_table['GPSInfo'][2]

    if lat_dir[0] == "S":
        sgn = -1
    else:
        sgn = 1

    lat = sgn * (float(lat[0][0]) + float(lat[1][0]) / 60.0 +
                 float(lat[2][0]) / 100.0 / 3600.0)
    lat = float("{:.6f}".format(lat))

    # 経度lonの読み取り。Eを正、Wを負として処理する。
    lon_dir = exif_table['GPSInfo'][3]
    lon = exif_table['GPSInfo'][4]

    if lon_dir[0] == "W":
        sgn = -1
    else:
        sgn = 1

    lon = sgn * (float(lon[0][0]) + float(lon[1][0]) / 60.0 +
                 float(lon[2][0]) / 100.0 / 3600.0)
    lon = float("{:.6f}".format(lon))
    return lat, lon
示例#30
0
def parse_exif(exif):
    exifData = {}
    if exif:
        for (tag, value) in exif.items():
            if value:
                decoded_tag = TAGS.get(tag, tag)
                if decoded_tag != 'GPSInfo':
                    exifData[decoded_tag] = value
                else:
                    for (key, val) in GPSTAGS.items():
                        if key in exif[tag]:
                            exifData[val] = exif[tag][key]
                            # Note: GPS Latitude and Longitude are represented in true rational64u format
    if 'GPSLatitude' in exifData.keys() and 'GPSLongitude' in exifData.keys():
        parse_coordinates(exifData)
        parse_location(exifData)
    return exifData
示例#31
0
    def get_exif_of_image(self, file):
        im = Image.open(file)

        try:
            exif = im._getexif()
        except AttributeError:
            return {}

        if exif == None:
            return {}

        exif_table = {}
        for tag_id, value in exif.items():
            tag = TAGS.get(tag_id, tag_id)
            exif_table[tag] = value

        return exif_table
示例#32
0
def get_date_from_exif(file):
    im = Image.open(file)
    exif = im._getexif()

    exif_table = {}
    for tag_id, value in exif.items():
        tag = TAGS.get(tag_id, tag_id)
        exif_table[tag] = value

    date_time = exif_table.get("DateTimeOriginal")
    # 'yyyy:mm:dd hh:mm:ss'というフォーマットなので
    # split(" ")により" "で分割し、最初の要素(日付に関する部分)のみ取得
    date = date_time.split(" ")[0]
    # ディレクトリ作成用にフォーマットを'yyyy:mm:dd'から'yyyy-mm-dd'に変更
    date = "-".join(date.split(":"))

    return date
示例#33
0
    def get_exif_data(image):
        exif_data = {}
        info = image._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for gps_tag in value:
                        sub_decoded = GPSTAGS.get(gps_tag, gps_tag)
                        gps_data[sub_decoded] = value[gps_tag]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value

        return exif_data
def get_exif_data(filename):
    """Get embedded EXIF data from image file.

    Source: <a href="http://www.endlesslycurious.com/2011/05/11/extracting-image-">http://www.endlesslycurious.com/2011/05/11/extract...</a>             exif-data-with-python/
    """
    ret = {}
    try:
        img = Image.open(filename)
        if hasattr( img, '_getexif' ):
            exifinfo = img._getexif()
            if exifinfo != None:
                for tag, value in exifinfo.items():
                    decoded = TAGS.get(tag, tag)
                    ret[decoded] = value
    except IOError:
        print ('IOERROR ' + filename)
    return ret
示例#35
0
def get_exif_of_image(file):
    """Get EXIF of an image if exists.

    指定した画像のEXIFデータを取り出す関数
    @return exif_table Exif データを格納した辞書
    """
    im = Image.open(file)

    # Exif データを取得
    # 存在しなければそのまま終了 空の辞書を返す
    try:
        exif = im._getexif()
    except AttributeError:
        return []

    # タグIDそのままでは人が読めないのでデコードして
    # テーブルに格納する
    exif_table = {}

    for tag_id, value in exif.items():
        tag = TAGS.get(tag_id, tag_id)
        exif_table[tag] = value

    data_requried = [
        "Model", "LensModel", "ExposureTime", "FNumber", "ISOSpeedRatings",
        "Orientation"
    ]
    exif_data = {}
    for id in data_requried:
        try:
            if id == "Model" or id == "LensModel":
                exif_data[id] = exif_table[id]
            elif id == "ExposureTime":
                exif_data[id] = str(exif_table["ExposureTime"][0]) + "/" + str(
                    exif_table["ExposureTime"][1])
            elif id == "FNumber":
                exif_data[id] = "F" + str(
                    exif_table["FNumber"][0] / exif_table["FNumber"][1])
            elif id == "ISOSpeedRatings":
                exif_data[id] = "ISO " + str(exif_table["ISOSpeedRatings"])
            #縦横判別情報も一緒に取り出しておく
            elif id == "Orientation":
                exif_data[id] = exif_table["Orientation"]
        except KeyError:
            pass
    return exif_data
示例#36
0
    def exif(self):
        exif_data = cache.get(self.exif_cache_key())
        if exif_data is None:
            data = {}
            try:
                photo = Image.open(self.file)
                info = photo._getexif()
                for tag, value in info.items():
                    decoded = TAGS.get(tag, tag)
                    data[decoded] = value

                cache.set(self.exif_cache_key(), data)
                exif_data = data
            except:
                exif_data = None

        return exif_data
示例#37
0
 def ExactImageMetadata(self, path):
     # path to the image or video
     imagename = path
     # read the image data using PIL
     image = Image.open(imagename)
     # extract EXIF data
     exifdata = image.getexif()
     #print(exifdata)
     # iterating over all EXIF data fields
     for tag_id in exifdata:
         # get the tag name, instead of human unreadable tag id
         tag = TAGS.get(tag_id, tag_id)
         data = exifdata.get(tag_id)
         # decode bytes
         if isinstance(data, bytes):
             data = data.decode()
         print(f"{tag:25}: {data}")
示例#38
0
    def update_exif(self):
        exif_data = {}
        self.data.open()
        with pImage.open(self.data) as img:
            if hasattr(img, '_getexif'):
                info = img.getexif()
                if not info:
                    return {}
                for tag, value in info.items():
                    decoded = TAGS.get(tag, tag)
                    exif_data[decoded] = value
                # Process some data for easy rendering in template
                exif_data['Camera'] = exif_data.get('Model', '')
                if exif_data.get(
                        'Make', ''
                ) not in exif_data['Camera']:  # Work around for Canon
                    exif_data['Camera'] = "{0} {1}".format(
                        exif_data['Make'].title(), exif_data['Model'])
                if 'FNumber' in exif_data:
                    exif_data['Aperture'] = str(
                        exif_data['FNumber'].numerator /
                        exif_data['FNumber'].denominator)
                if 'ExposureTime' in exif_data:
                    exif_data['Exposure'] = "{0}/{1}".format(
                        exif_data['ExposureTime'].numerator,
                        exif_data['ExposureTime'].denominator)
            img.close()

        self.exif_camera = exif_data.get('Camera')
        self.exif_lens = exif_data.get('LensModel')
        self.exif_focal_length = exif_data.get('FocalLengthIn35mmFilm')
        self.exif_aperture = exif_data.get('Aperture')
        self.exif_exposure = exif_data.get('Exposure')
        self.exif_iso = exif_data.get('ISOSpeedRatings')

        self.exif_date_taken = None
        original_exif = exif_data.get('DateTimeOriginal')
        if original_exif:
            try:
                # EXIF is not timezone aware, but Django requires a timezone, so the best we can do is assume UTC
                date_taken = datetime.strptime(original_exif,
                                               "%Y:%m:%d %H:%M:%S")
                self.exif_date_taken = timezone.make_aware(
                    date_taken, pytz.timezone('UTC'))
            except ValueError:  # Fall back to file modification time
                pass
示例#39
0
def testForExif(imgFileName):
    try:
        exifData = {}
        imgFile = Image.open(imgFileName)
        print("GetExif()")
        info = imgFile._getexif()
        if info:
            for (tag, value) in info.items():
                decoded = TAGS.get(tag, tag)
                exifData[decoded] = value
            exifGPS = exifData['GPSInfo']
            if exifGPS:
                print("[*] " + imgFileName + ' contains GPS MetaData')
            else:
                print("[-] No MetaData found for these images")
    except:
        pass
示例#40
0
    def open_exif(self, img):

        exif = img._getexif()
        ret = {}
        gps = {}
        for tag, value in exif.items():
            decoded = TAGS.get(tag, tag)
            ret[decoded] = value
            # Getting GPS lat, long
            if decoded == "GPSInfo":
                gps_data = {}
                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps_data[sub_decoded] = value[t]

                gps[decoded] = gps_data
        return ret, gps
示例#41
0
def get_exif(image_file_path):
    exif_table = {}
    image = Image.open(image_file_path)
    info = image.getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        exif_table[decoded] = value

    gps_info = {}
    for key in exif_table['GPSInfo']:
        decode = GPSTAGS.get(key, key)
        gps_info[decode] = exif_table['GPSInfo'][key]

    if gps_info:
        return gps_info
    else:
        return "No GPS data found!"
    def get_exif_data(self):
        exif_data = {}
        info = self.image._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        self.exif_data = exif_data
        return exif_data
示例#43
0
def get_image_tags(file_path):
    u""" Получить тэги изображения (EXIF) """
    img = Image.open(file_path)

    if not hasattr(img, '_getexif'):
        return {}

    info = img._getexif()
    if not info:
        return {}

    res = {}
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        res[decoded] = value

    return res
 def _get_pair(self, scene, map_path, img_path):
     uav_pil_img = Image.open(img_path)
     exifdata = uav_pil_img.getexif()
     for tag_id in exifdata:
         tag = TAGS.get(tag_id, tag_id)
         if re.match(r'.*GPS.*', str(tag)):
             info = exifdata.get(tag_id)
             lat = info[2]
             lon = info[4]
             break
     uav_img_arr = np.array(uav_pil_img)
     uav_loc = decimal_gps(lon, lat)
     map_img_arr = cv.imread(map_path)
     map_img_arr = cv.cvtColor(map_img_arr, cv.COLOR_BGR2RGB)
     map_geo = self._map_geo.loc[scene,
                                 ['left', 'top', 'right', 'bottom']].values
     return uav_img_arr, uav_loc, map_img_arr, map_geo
示例#45
0
def get_gps_data(i):
    info = i._getexif()
    exif_data = {}
    lat = np.nan
    lon = np.nan
    alt = np.nan
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        if decoded == "GPSInfo":
            gps_data = {}
            for t in value:
                sub_decoded = GPSTAGS.get(t, t)
                gps_data[sub_decoded] = value[t]

            lat, lon, alt = latlon_from_gps_data(gps_data)

    return lat, lon, alt
示例#46
0
 def parseExif(self):
     img = Image.open(self.fp)
     ret = {}
     if hasattr(img, '_getexif'):
         exifinfo = img._getexif()
         if exifinfo != None:
             for tag, value in exifinfo.items():
                 decoded = TAGS.get(tag, tag)
                 if isinstance(value, type("123")):
                     try:
                         value = value.decode()
                     except:
                         value = ""
                 ret[decoded] = value
             self.exif = ret
             return ret
     return {}
示例#47
0
def get_exif(filename):
    exif = Image.open(filename)._getexif()
    #print(type(exif))

    if exif is not None:
        exif_copy = exif.copy()
        for key, value in exif_copy.items():
            name = TAGS.get(key, key)
            exif[name] = exif.pop(key)

        new_exif = {}
        if 'GPSInfo' in exif:
            for key in exif['GPSInfo'].keys():
                name = GPSTAGS.get(key, key)
                new_exif[name] = exif['GPSInfo'][key]

        return new_exif
示例#48
0
def testForExif(imgFileName):
    try:
        exifData = {}
        imgFile = Image.open(imgFileName)
        info = imgFile._getexif()

        if info:
            for (tag, value) in info.items():
                decoded = TAGS.get(tag, tag)
                exifData[decoded] = value

            exifGPS = exifData['GPSInfo']
            if exifGPS:
                print '[*] ' + imgFileName + ' contains GPS meta data'

    except:
        pass
示例#49
0
    def get_exif_data(self):
        exif_data = {}
        with open(self.filepath, 'rb') as infile:
            tags = exifread.process_file(infile)
            for tag, value in tags.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = str(value)
        # self._exif_data = exif_data
        return exif_data
示例#50
0
def writeLists(D):
    outfile = open(D + "list.txt", 'w')
    for f in os.listdir(D):
        if f.endswith(".jpg"):

            img = Image.open(D + f)
            exif_data = {}
            info = img._getexif()
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                exif_data[decoded] = value

            nominator = exif_data["ExposureTime"][1] / exif_data[
                "ExposureTime"][0]

            outfile.write(f + "\t" + str(nominator) + "\n")
    outfile.close()
    def identify_tags(self, infile: str) -> dict:
        """Read infile, return dict with relevant tags."""
        _tags = {}
        logging.debug(f"identify_tags: {infile}")

        with Image.open(infile) as im:
            exifdata = im.getexif()
            for tag_id in exifdata:
                # get the tag name, instead of human unreadable tag id
                tag = TAGS.get(tag_id, tag_id)
                data = exifdata.get(tag_id)
                if tag == "DateTime":
                    _tags[tag] = data
                logging.debug(f"Tag: {tag} - data: {data}")

        logging.debug(f"Return tags: {_tags}")
        return _tags
示例#52
0
def get_exif_data(fn):
    """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
    exif_data = {}
    i = Image.open(fn)
    info = i._getexif()
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                gps_data = {}
                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps_data[sub_decoded] = value[t]
                exif_data[decoded] = gps_data
            else:
                exif_data[decoded] = value
    return exif_data
示例#53
0
def get_exif_data(image):
    #get exif data from the image
    exif_data = {}
    info = image._getexif()
    if info:
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            if decoded == "GPSInfo":
                gps_data = {}
                for t in value:
                    sub_decoded = GPSTAGS.get(t, t)
                    gps_data[sub_decoded] = value[t]

                exif_data[decoded] = gps_data
            else:
                exif_data[decoded] = value
    return exif_data
示例#54
0
    def retrieveExifData(self, file):
        exifDictionary = {}
        fileHandle = None

        try:
            fileHandle = Image.open(file, "r")
            exifInfo = fileHandle._getexif()

            for tag, value in exifInfo.items():
                retrieved = TAGS.get(tag, tag)
                exifDictionary[retrieved] = value

            utility.logStringToFile(self.validFilesOutputFile, 'a', str('FileName: ' + str(file) + '\n'))
        except Exception as e:
            utility.logStringToFile(self.invalidFilesOutputFile, 'a', str('FileName: ' + str(file) + '\n'))

        return exifDictionary
示例#55
0
    def _extract_exif(self):
        ret = {}
        # ipdb.set_trace()
        i = PIL.Image.open(self.image_path)
        info = i._getexif()
        for tag, value in info.items():
            decoded = EXIFTAGS.get(tag, tag)
            ret[decoded] = value

        with open(self.image_path, 'rb') as fimg:
            exif = exifread.process_file(fimg, details=False)

            serializable = dict([key, value.printable]
                                for key, value in exif.items())
            self.exif_json = serializable
            # ipdb.set_trace()
            if 'EXIF DateTimeOriginal' in exif.keys():
                tst_str = exif['EXIF DateTimeOriginal'].values
                try:
                    tst_dt = datetime.strptime(tst_str, "%Y:%m:%d %H:%M:%S")
                except:
                    tst_dt = datetime.strptime(tst_str, "%Y-%m-%d %H:%M:%S")
                # ipdb.set_trace()
                self.exif_timestamp = tst_dt

            else:
                self.exif_timestamp = None

            if 'GPS GPSLongitude' in exif.keys():
                self.exif_gps_lon = util.convert_to_degrees(
                    exif['GPS GPSLongitude'].values)
                # Check for correct positive/negative degrees
                if exif['GPS GPSLongitudeRef'].values != 'E':
                    self.exif_gps_lon = -self.exif_gps_lon
            else:
                self.exif_gps_lon = None

            if 'GPS GPSLatitude' in exif.keys():
                self.exif_gps_lat = util.convert_to_degrees(
                    exif['GPS GPSLatitude'].values)
                # Check for correct positive/negative degrees
                if exif['GPS GPSLatitudeRef'].values != 'N':
                    self.exif_gps_lat = -self.exif_gps_lat
            else:
                self.exif_gps_lat = None
示例#56
0
def process_image(file):
    rfname = os.path.join(temp_dir, str(uuid.uuid4()) + os.path.splitext(file.name)[1])
    try:
        f = open(rfname, 'wb')
        fname = str(uuid.uuid4()) + os.path.splitext(file.name)[-1].lower()
        small = '%s.small%s' % os.path.splitext(fname)
        while True:
            data = file.file.read(8192)
            f.write(data)
            if not data:
                break
        f.close()
        img = Image.open(rfname)

        img.thumbnail((500, 500))
        try:
            exif = img._getexif()
            if exif:
                exif = {TAGS.get(k): v for k, v in exif.items()}
                if 'Orientation' in exif:
                    orientation = exif['Orientation']
                    if orientation == 6:
                        img = img.rotate(-90)
                    elif orientation == 8:
                        img = img.rotate(90)
                    elif orientation == 3:
                        img = img.rotate(180)
        except:
            pass

        r = fname
        fname = os.path.join(dest_dir, fname)
        small = os.path.join(dest_dir, small)

        img.save(fname)
        img.thumbnail((120, 120))
        img.save(small)
        img.close()
    finally:
        if os.path.isfile(rfname):
            os.unlink(rfname)
    return {
        'image': 'tmp/' + r,
        'small': 'tmp/' + os.path.basename(small),
    }
示例#57
0
def image_view(request):

    if request.method == 'POST':

        form = ImageForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            print(form.cleaned_data)
            image_table = db.image_image
            filename = str(form.cleaned_data['image'])
            image_id = image_table.find_one(
                {'image': 'images' + '/' + filename})['id']
            path = 'media/images/' + filename
            size = os.path.getsize(path) / (1024 * 1024)
            image = Image.open(path)
            exifdata = image.getexif()
            metadata = {"name": filename, 'id': image_id, 'size': int(size)}
            for tag_id in exifdata:
                # get the tag name, instead of human unreadable tag id
                tag = TAGS.get(tag_id, tag_id)
                data = exifdata.get(tag_id)
                # decode bytes
                if isinstance(data, bytes):
                    data = data.decode()
                print(f"{tag}: {data}")

                try:
                    metadata.update({tag: float(str(data))})
                except:
                    metadata.update({tag: str(data)})

            metacollection = db.metacollection
            result = metacollection.insert_one(metadata)
            print('One post: {0}'.format(result.inserted_id))
            data = {
                'success': True,
                'message': 'Upload and metadata extraction succesful',
                'form': ImageForm()
            }
            return render(request, 'upload.html', data)
    else:
        form = ImageForm()
    data = {'form': form, 'success': False}
    return render(request, 'upload.html', data)
示例#58
0
def get_exif(imgFileName):
    pp = pprint.PrettyPrinter(indent=4)

    try:
        exifData = {}
        imgFile = Image.open(imgFileName)
        info = imgFile._getexif()

        if info:
            for (tag, value) in info.items():
                decoded = TAGS.get(tag, tag)
                exifData[decoded] = value

            for key, value in exifData.iteritems():
                if key == 'GPSInfo':
                    print Style.BRIGHT + Fore.GREEN + "GPS Info:" + Style.RESET_ALL
                    pp.pprint(value)

                if key == 'Manufacturer':
                    print Style.BRIGHT + Fore.GREEN + "Manufacturer:" + Style.RESET_ALL
                    print value

                if key == 'Model':
                    print Style.BRIGHT + Fore.GREEN + "Model:" + Style.RESET_ALL
                    print value

                if key == 'Make':
                    print Style.BRIGHT + Fore.GREEN + "Make:" + Style.RESET_ALL
                    print value

                if key == 'Software':
                    print Style.BRIGHT + Fore.GREEN + "Software:" + Style.RESET_ALL
                    print value

                if key == 'DateTimeOriginal':
                    print Style.BRIGHT + Fore.GREEN + "Date Created:" + Style.RESET_ALL
                    print value

                if key == 'Creating Application':
                    print Style.BRIGHT + Fore.GREEN + "Creating Application:" + Style.RESET_ALL
                    print value
        else:
            pass
    except:
        pass
示例#59
-1
文件: info.py 项目: realyasswl/vc
def get_exif_data(image):
    """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""

    try:
        info = image._getexif()
    except AttributeError:
        return {}
    if not info:
        return {}
    exif_data = {TAGS.get(tag, tag): value for tag, value in info.items()}

    def is_fraction(val):
        return isinstance(val, tuple) and len(val) == 2 and isinstance(val[0], int) and isinstance(val[1], int)

    def frac_to_dec(frac):
        return float(frac[0]) / float(frac[1])

    if "GPSInfo" in exif_data:
        gpsinfo = {GPSTAGS.get(t, t): v for t, v in exif_data["GPSInfo"].items()}
        for tag, value in gpsinfo.items():
            if is_fraction(value):
                gpsinfo[tag] = frac_to_dec(value)
            elif all(is_fraction(x) for x in value):
                gpsinfo[tag] = tuple(map(frac_to_dec, value))
        exif_data["GPSInfo"] = gpsinfo
    return exif_data
示例#60
-1
def get_exif_data(image):
    """
    Returns a dictionary from the exif data of an PIL Image item.
    Also converts the GPS Tags
    https://gist.github.com/valgur/2fbed04680864fab1bfc
    """

    info = image._getexif()
    if not info:
        return {}
    exif_data = {TAGS.get(tag, tag): value for tag, value in info.items()}

    def is_fraction(val):
        return isinstance(val, tuple) and len(val) == 2 and isinstance(
            val[0], int) and isinstance(val[1], int)

    def frac_to_dec(frac):
        return float(frac[0]) / float(frac[1])

    if 'GPSInfo' in exif_data:
        gpsinfo = {GPSTAGS.get(t, t): v
                   for t, v in exif_data['GPSInfo'].items()}
        for tag, value in gpsinfo.items():
            if is_fraction(value):
                gpsinfo[tag] = frac_to_dec(value)
            elif all(is_fraction(x) for x in value):
                gpsinfo[tag] = tuple(map(frac_to_dec, value))
        exif_data['GPSInfo'] = gpsinfo

    return exif_data