def add_key_frames(request, image_sequence_id): try: image_sequence = ImageSequence.objects.get(pk=image_sequence_id) except ImageSequence.DoesNotExist: raise Http404('Image sequence does not exist') if request.method == 'POST': frame_list = request.POST.getlist('frames') if len(frame_list) == 0: messages.error(request, 'You must select at least 1 frame') else: # Add frames to db for frame_nr in frame_list: # Create image image = Image() image.filename = image_sequence.format.replace('#', str(frame_nr)) image.dataset = image_sequence.dataset image.save() # Create associated key frame key_frame = KeyFrame() key_frame.frame_nr = int(frame_nr) key_frame.image_sequence = image_sequence key_frame.image = image key_frame.save() messages.success(request, 'The image sequence and frames were stored.') return redirect('annotation:datasets') return render(request, 'annotation/add_key_frames.html', {'image_sequence': image_sequence})
def import_images(path, dataset): for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, '*.png'): image = Image() image.filename = os.path.join(root, filename) image.dataset = dataset image.save() print('Saved image ', image.filename)
def create_derived_image(image,pilDerivedImage,type,eraseOldVersions = True): if eraseOldVersions: image.derived_images.filter(type = type).delete() (directory,basename,extension) = image.splitPath() derivedImageFilename = basename+"_"+type+"."+extension derivedImagePath = directory+"/"+derivedImageFilename cnt = 1 while os.path.exists(derivedImagePath): derivedImageFilename = basename+"_"+type+("_%d" % cnt)+"."+extension derivedImagePath = directory+"/"+derivedImageFilename cnt+=1 derivedImageUrl = settings.FILE_UPLOAD_URL+"/"+derivedImageFilename pilDerivedImage.save(derivedImagePath) derivedImage = Image() derivedImage.path = derivedImagePath derivedImage.user = image.user derivedImage.base_image = image derivedImage.type = type derivedImage.url = derivedImageUrl derivedImage.width = pilDerivedImage.size[0] derivedImage.height = pilDerivedImage.size[1] derivedImage.save() return derivedImage
def save_img(img: Image, img_name: str): """ Save the given image to the image directory :param img: Image object :param img_name: Name including the extension of the image, excluding the directory """ full_img_path = os.path.join(img_dir(), img_name) img.save(full_img_path)
def get_compressed_size(image: Image, quality) -> float: """Find the size of an image after JPEG compression. :param image: Image to compress. :param quality: JPEG compression quality (1-100). """ with BytesIO() as fh: image.save(fh, 'JPEG', quality=quality) size = len(fh.getvalue()) return size
def upload_image(imageData,user = None,save = True,path = None): try: extension = re.search(r"\.(\w+)$",imageData.name).group(1) except: raise Exception("Cannot determine extension from filename: %s" % imageData.name) try: temporaryPath = generate_random_filename(settings.FILE_TEMPORARY_UPLOAD_PATH,extension) if path: (directory,filename) = os.path.split(path) match = re.search(r"^(.*)\.(\w+)$",filename) imageFilenameKey = match.group(1) else: imageFilenameKey = generate_random_filename_key(settings.FILE_UPLOAD_PATH,extension = "jpg") imagePath = settings.FILE_UPLOAD_PATH+"/"+imageFilenameKey+"."+settings.IMAGE_EXTENSION imageUrl = settings.FILE_UPLOAD_URL+"/"+imageFilenameKey+"."+settings.IMAGE_EXTENSION temporaryFile = open(temporaryPath,'wb') for chunk in imageData.chunks(): temporaryFile.write(chunk) temporaryFile.close() try: pilImage = PIL.Image.open(temporaryPath) aspectRatio = float(pilImage.size[0])/float(pilImage.size[1]) if aspectRatio > 1.: aspectRatio = 1./aspectRatio if aspectRatio < settings.IMAGE_MINIMUM_ASPECT_RATIO: raise AspectRatioException("Aspect ratio of the image is too small!") pilRescaledImage = shrink_image(pilImage,settings.IMAGE_MAXIMUM_DIMENSIONS) pilRescaledImage.save(imagePath,settings.IMAGE_FORMAT) image = Image() image.user = user image.path = imagePath image.url = imageUrl image.width = pilRescaledImage.size[0] image.height = pilRescaledImage.size[1] if save: image.save() return image except: raise finally: if os.path.exists(temporaryPath): os.remove(temporaryPath)
def upload_image( image_data, extension, description, album, photographer, credits, licence, content_type, tags, uploader ): """Note that the provided file extension will be standardized and may change, so callers should take care to use the extension of the returned image object if needed further.""" conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(settings.AWS_S3_BUCKET) image_key = Image.generate_unique_random_key() pil_image = PIL.Image.open(BytesIO(image_data)) extension = standardize_extension(extension) # cannot write P mode as JPEG; see http://stackoverflow.com/q/21669657/302484 if extension == "jpeg" and pil_image.mode == "P": pil_image = pil_image.convert("RGB") exif_json = json.dumps(get_exif_tags(image_data)) image_file_tags = xmp.find_keywords(image_data) thumbs = [{"size": size, "data": create_thumb(pil_image, extension, size)} for size in settings.THUMB_SIZES] key = bucket.new_key("%s/%s.%s" % (settings.AWS_S3_FOLDERS["imagearchive"], image_key, extension)) key.content_type = content_type key.set_contents_from_string(image_data, policy="public-read") for thumb in thumbs: key = bucket.new_key( "%s/%s-%s.%s" % (settings.AWS_S3_FOLDERS["imagearchive"], image_key, thumb["size"], extension) ) key.content_type = content_type key.set_contents_from_string(thumb["data"], policy="public-read") image = Image( key=image_key, extension=extension, hash=sha1(image_data).hexdigest(), description=description, album=album, photographer=photographer, credits=credits, licence=licence, exif=exif_json, uploader=uploader, width=pil_image.size[0], height=pil_image.size[1], ) image.save() for tag in [tag.lower() for tag in image_file_tags + tags]: obj, created = Tag.objects.get_or_create(name=tag) image.tags.add(obj) return image
def upload_image(image_data, extension, description, album, photographer, credits, licence, content_type, tags, uploader): """Note that the provided file extension will be standardized and may change, so callers should take care to use the extension of the returned image object if needed further.""" conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(s3_bucket()) image_key = Image.generate_unique_random_key() pil_image = PIL.Image.open(StringIO(image_data)) extension = standardize_extension(extension) # cannot write P mode as JPEG; see http://stackoverflow.com/q/21669657/302484 if extension == 'jpeg' and pil_image.mode == 'P': pil_image = pil_image.convert('RGB') exif_json = json.dumps(get_exif_tags(pil_image)) image_file_tags = xmp.find_keywords(image_data) thumbs = [{'size': size, 'data': create_thumb(pil_image, extension, size)} for size in settings.THUMB_SIZES] # Give boto an encoded str, not unicode if type(content_type) == unicode: content_type = content_type.encode('utf-8') key = bucket.new_key("%s%s.%s" % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, extension)) key.content_type = content_type key.set_contents_from_string(image_data, policy='public-read') for thumb in thumbs: key = bucket.new_key("%s%s-%s.%s" % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, thumb['size'], extension)) key.content_type = content_type key.set_contents_from_string(thumb['data'], policy='public-read') image = Image( key=image_key, extension=extension, hash=sha1(image_data).hexdigest(), description=description, album=album, photographer=photographer, credits=credits, licence=licence, exif=exif_json, uploader=uploader, width=pil_image.size[0], height=pil_image.size[1]) image.save() for tag in [tag.lower() for tag in image_file_tags + tags]: obj, created = Tag.objects.get_or_create(name=tag) image.tags.add(obj) return image
def create_image(pil_img, **kwargs): """ Given an image (PIL format) and some metadata, write to file sys and create DB entry pil_img: PIL.Image (see https://pillow.readthedocs.org/en/latest/reference/Image.html) """ # get DB info for image random_uuid = str(uuid.uuid4()) security_marking = kwargs.get('security_marking', 'UNCLASSIFIED') file_extension = kwargs.get('file_extension', 'png') valid_extensions = constants.VALID_IMAGE_TYPES if file_extension not in valid_extensions: logger.error('Invalid image type: %s' % file_extension) # TODO: raise exception? return image_type = kwargs.get('image_type', None) if not image_type: logger.error('No image_type provided') # TODO raise exception? return image_type = ImageType.objects.get(name=image_type) # create database entry img = Image(uuid=random_uuid, security_marking=security_marking, file_extension=file_extension, image_type=image_type) img.save() # write the image to the file system file_name = settings.MEDIA_ROOT + str(img.id) + '_' + img.image_type.name + '.' + file_extension # logger.debug('saving image %s' % file_name) pil_img.save(file_name) # check size requirements size_bytes = os.path.getsize(file_name) # TODO: PIL saved images can be larger than submitted images. # To avoid unexpected image save error, make the max_size_bytes # larger than we expect if size_bytes > (image_type.max_size_bytes * 2): logger.error('Image size is %d bytes, which is larger than the max \ allowed %d bytes' % (size_bytes, 2 * image_type.max_size_bytes)) # TODO raise exception and remove file return # TODO: check width and height return img
def _assert_expected_exif(self, case): with open(case["source_path"], "rb") as f: img = Image(f).resize(case["width"], case["height"]) rv = img.save(preserve_exif=case["preserve_exif"]) with open(case["expected_path"], "rb") as expected: msg = "{} does not match {}".format(case["source_path"], case["expected_path"]) self.assertEqual(rv.read(), expected.read(), msg)
def test_save_failure(self): img = Image(os.path.join(DATADIR, 'test5.gif')) def _mock_save(*args, **kwargs): raise IOError('foo') img.img.save = _mock_save self.assertRaises(errors.ImageSaveError, lambda: img.save(format="webp"))
def _assert_expected_region(self, case): with open(case["source_path"], "rb") as f: img = Image(f).region(case["rect"].split(",")) rv = img.save( format=case.get("format"), quality=case.get("quality")) with open(case["expected_path"], "rb") as expected: msg = "%s does not match %s" \ % (case["source_path"], case["expected_path"]) self.assertEqual(rv.read(), expected.read(), msg)
def _assert_expected_region(self, case): with open(case["source_path"], "rb") as f: img = Image(f).region(case["rect"].split(",")) rv = img.save( format=case.get("format"), optimize=case.get("optimize"), progressive=case.get("progressive"), quality=case.get("quality"), ) with open(case["expected_path"], "rb") as expected: msg = "{} does not match {}".format(case["source_path"], case["expected_path"]) self.assertEqual(rv.read(), expected.read(), msg)
def _assert_expected_rotate(self, case): with open(case["source_path"], "rb") as f: img = Image(f).rotate(case["degree"], expand=case.get("expand"), filter=case.get("filter")) rv = img.save( format=case.get("format"), optimize=case.get("optimize"), progressive=case.get("progressive"), quality=case.get("quality"), ) with open(case["expected_path"], "rb") as expected: msg = "{} does not match {}".format(case["source_path"], case["expected_path"]) self.assertEqual(rv.read(), expected.read(), msg)
def get_type_instance(self): """ Return related Image, Video etc. object. If object doesn't exist yet, create new one and return it, if possible. """ if self.mimetype.startswith("image"): try: return self.image except Image.DoesNotExist: image = Image(content=self) image.save() # Save new instance to the database return image elif self.mimetype.startswith("video"): try: return self.video except Video.DoesNotExist: video = Video(content=self) video.save() # Save new instance to the database return video else: return None
def _assert_expected_resize(self, case): with open(case["source_path"], "rb") as f: img = Image(f).resize( case["width"], case["height"], mode=case["mode"], background=case.get("background"), filter=case.get("filter"), position=case.get("position")) rv = img.save( format=case.get("format"), quality=case.get("quality")) with open(case["expected_path"], "rb") as expected: msg = "%s does not match %s" \ % (case["source_path"], case["expected_path"]) self.assertEqual(rv.read(), expected.read(), msg)
def _assert_expected_rotate(self, case): with open(case["source_path"], "rb") as f: img = Image(f).rotate( case["degree"], expand=case.get("expand"), filter=case.get("filter")) rv = img.save( format=case.get("format"), quality=case.get("quality")) with open(case["expected_path"], "rb") as expected: msg = "%s does not match %s" \ % (case["source_path"], case["expected_path"]) self.assertEqual(rv.read(), expected.read(), msg)
def _assert_expected_chained(self, case): with open(case["source_path"], "rb") as f: img = Image(f) for operation in case["operation"]: if operation == "resize": img.resize(case["width"], case["height"]) elif operation == "rotate": img.rotate(case["degree"]) elif operation == "region": img.region(case["rect"].split(",")) rv = img.save() with open(case["expected_path"], "rb") as expected: msg = "{} does not match {}".format(case["source_path"], case["expected_path"]) self.assertEqual(rv.read(), expected.read(), msg)
def _assert_expected_resize(self, case): with open(case["source_path"], "rb") as f: img = Image(f).resize( case["width"], case["height"], mode=case["mode"], background=case.get("background"), filter=case.get("filter"), position=case.get("position"), retain=case.get("retain"), ) rv = img.save( format=case.get("format"), optimize=case.get("optimize"), progressive=case.get("progressive"), quality=case.get("quality"), ) with open(case["expected_path"], "rb") as expected: msg = "{} does not match {}".format(case["source_path"], case["expected_path"]) self.assertEqual(rv.read(), expected.read(), msg)
def pic2b64(pic: Image) -> str: buf = BytesIO() pic.save(buf, format='PNG') base64_str = base64.b64encode(buf.getvalue()).decode() return 'base64://' + base64_str
def _save_result_image(self, source_path: Path, image: Image) -> Path: result_path = self.results_dir / source_path.name image.save(result_path) return result_path
def image_to_byte_array(image: Image): imgByteArr = io.BytesIO() image.save(imgByteArr, format=image.format) imgByteArr = imgByteArr.getvalue() return imgByteArr
def _convert_image_to_png(image: PillowImage) -> io.BytesIO: bytes_io = io.BytesIO() image.save(bytes_io, format="png") bytes_io.seek(0) return bytes_io
def fileFromImage(Image, format="jpeg"): newfile = io.BytesIO() Image.save(newfile, format=format) newfile.seek(0) return newfile
def frame_to_png_bytes(image: Image) -> io.BytesIO: """Convert image to byte stream.""" stream = io.BytesIO() image.save(stream, format="PNG") stream.seek(0) return stream
def image_to_byte_array(image: Image) -> bytes: """Convert pil image to bytes""" imgByteArr = io.BytesIO() image.save(imgByteArr, format="png") imgByteArr = imgByteArr.getvalue() return imgByteArr
def save(outfile): try: Image.save(outfile) except IOError: print("cannot save", outfile)
def save(mosaic: Image): files = [('Jpeg Files', '*.jpg')] file = asksaveasfile(filetypes=files, defaultextension=files) if file is not None: mosaic.save(file.name, "JPEG")
def upload_image(request): try: if len(request.FILES.getlist('files')) == 0: result = json.dumps({'status': 'no_files'}) return render(request, 'central/admin/images/iframe.html', {'result': result}) conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(settings.AWS_S3_BUCKET) ids = [] album = None if request.POST['album'] == '' else Album.objects.get(id=request.POST['album']) for image in request.FILES.getlist('files'): image_key = Image.generate_unique_random_key() data = image.read() ext = image.name.split(".")[-1].lower() pil_image = PIL.Image.open(BytesIO(data)) exif_json = json.dumps(get_exif_tags(data)) tags = xmp.find_keywords(data) thumbs = [{'size': size, 'data': create_thumb(pil_image, ext, size)} for size in settings.THUMB_SIZES] key = bucket.new_key("%s/%s.%s" % (settings.AWS_S3_FOLDERS['imagearchive'], image_key, ext)) key.content_type = image.content_type key.set_contents_from_string(data, policy='public-read') for thumb in thumbs: key = bucket.new_key("%s/%s-%s.%s" % ( settings.AWS_S3_FOLDERS['imagearchive'], image_key, thumb['size'], ext )) key.content_type = image.content_type key.set_contents_from_string(thumb['data'], policy='public-read') image = Image( key=image_key, extension=ext, hash=sha1(data).hexdigest(), description='', album=album, photographer='', credits='', licence='', exif=exif_json, uploader=request.user, width=pil_image.size[0], height=pil_image.size[1]) image.save() for tag in [tag.lower() for tag in tags]: obj, created = Tag.objects.get_or_create(name=tag) image.tags.add(obj) ids.append(image.id) result = json.dumps({ 'status': 'success', 'ids': ids }) return render(request, 'central/admin/images/iframe.html', {'result': result}) except(IOError, KeyError): logger.warning( "Kunne ikke parse opplastet bilde, antar at det er ugyldig bildefil", exc_info=sys.exc_info(), extra={'request': request} ) result = json.dumps({'status': 'parse_error'}) return render(request, 'central/admin/images/iframe.html', {'result': result}) except Exception: logger.error( "Ukjent exception ved bildeopplasting", exc_info=sys.exc_info(), extra={'request': request} ) result = json.dumps({'status': 'unknown_exception'}) return render(request, 'central/admin/images/iframe.html', {'result': result})
def to_base64(image: Image) -> str: buffered = BytesIO() image.save(buffered, format='PNG') img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") return img_str
def _encode_pil_image(image: Image) -> bytes: with io.BytesIO() as image_buffer: image.save(image_buffer, format="PNG") return image_buffer.getvalue()
def img_to_bytearray(Image): imgByteArr = io.BytesIO() Image.save(imgByteArr, format='PNG') return imgByteArr.getvalue()
def _save_result_image(self, source_path: Path, image: Image, results_dir = None) -> Path: if results_dir is None: results_dir = Path(self.results_dir) result_path = results_dir / source_path.name image.save(result_path) return result_path
def scrape_images(): config.read(os.path.join(gdg.current_dir, 'gdg.conf')) dbpath = get_directory(config.get('database', 'path')) dbfile = os.path.join(dbpath, 'gallery.db') print("Using database " + dbfile) if not os.path.isfile(dbfile): try: print("No database exists, initializing.") initscript = os.path.join(gdg.current_dir, 'gallery.sql') import io, sqlite3 conn = sqlite3.connect(dbfile) with open(initscript, 'r') as sql: script = sql.read() conn.executescript(script) conn.close() except Exception as ex: print("Unable to initialize database at {}: {}. Aborting.".format(dbfile, str(ex))) exit() with GoddamnDatabase(dbpath) as db: current = [i.path for i in Image.select()] imgpath = get_directory(config.get('images', 'path')) print("Searching {} for new images...".format(imgpath)) ondisk = get_image_files(imgpath, config.get('images', 'follow_links')) new_files = set(ondisk) - set(current) deleted_files = set(current) - set(ondisk) if len(new_files) > 0: with db.transaction(): for f in new_files: i = Image() g = os.path.dirname(os.path.relpath(f, imgpath)).replace('\\', '/') i.path = f i.gallery = g if g == '': i.parent = None else: i.parent = os.path.dirname(g) i.save() print("Added {} new images.".format(len(new_files))) if len(deleted_files) > 0: with db.transaction(): for f in deleted_files: img = Image.get(Image.path == f) try: if os.path.isfile(img.thumb): os.remove(img.thumb) except Exception as ex: print("Unable to delete thumbnail for deleted image: {}. You will need to remove this manually.".format(img.thumb)) img.delete_instance() print("Removed records for {} deleted images.".format(len(deleted_files))) # 2nd pass - derives metadata, etc # currently: if there's a thumbnail, assume all processing is complete. with GoddamnDatabase(dbpath) as db: q = Image.select().where(Image.thumb == None).naive() total = q.count() if total == 0: return thumb_path = get_directory(config.get('thumbnails', 'path')) thumb_prefix = config.get('thumbnails', 'prefix').translate(None, '"\'') thumb_postfix = config.get('thumbnails', 'postfix').translate(None, '"\'') thumb_aspect_ratio = config.get('thumbnails', 'aspect_ratio').translate(None, '"\'') pool = Pool() to_save = [] try: result = pool.map_async(scrape_image_data, [(i, thumb_path, thumb_prefix, thumb_postfix, thumb_aspect_ratio) for i in q.iterator()], 25) to_save = result.get() except KeyboardInterrupt: pool.terminate() print("Scrape halted.") return # Should this be a configuration variable? bsize = 50 for b in range(0, len(to_save), bsize): with db.transaction(): for i in to_save[b:b+bsize]: if i == None: continue try: i.save() except Exception as e: print("Error saving data for image {}: {}".format(i.path), str(ex))
def image_to_bytes(image: Image): img_bytes = io.BytesIO() image.save(img_bytes, 'PNG') return img_bytes.getvalue()
def store_result(image: Image, output_path: str, jpg_quality=95): print("Storing result at", output_path) image.save(output_path, quality=jpg_quality, subsampling=0)
# first last ITEC 1150-60. # This is my final project code that will generate a recipe book of taco # recipes including a random picture of taco and three randomly generated recipes import docx # import this library to create and update a word document import requests # to get the url from PIL import Image, ImageDraw, ImageFont # importing image and font Image = Image.open('photo-1552332386-f8dd00dc2f85.jpeg' ) # opening image that i will use for my project Image.thumbnail((800, 800)) # resizing the image not more or less than 800 Image.save('taco_thumbnails.jpeg') # saving the image img_draw = ImageDraw.Draw(Image) # drawing a text to the image font = ImageFont.truetype( 'DejaVuSans.ttf', 20) # using font color for the text that im using for the image # so i downloaded Dejavu from the website img_draw.text([200, 80], 'Random Taco Cookbook', fill='purple', font=font) # for the text in the picture, im using to draw a text in the image # the ' Random text cookbook' text [200, 80] and fill purple in the text Image.save('modified_taco.jpg') # saving the the taco image and naming it while it shows up in the image # next step im creating a list to store dictionaries in taco_book = [ ] # this list i will be using to create three dictionaries for my taco
def image_to_bytes(image:Image) -> io.BytesIO: image_to_send = io.BytesIO() image.save(image_to_send, "PNG") image_to_send.seek(0) return image_to_send
openwebex = "C:\\Program Files (x86)\\Webex\\Webex\\Applications\\ptoneclk.exe" os.startfile(openwebex) speakJarv("yes, i am arranging webex for you...") elif 'where i am' in query: speakJarv("Please wait...i am checking") try: ipadd = rq.get('https://.ipify.org').text print(ipadd) url = 'https://get.geojs.io/v1/ip/geo' + ipadd + '.json' georeq = rq.get(url) geodata = georeq.json() city = geodata['city'] country = geodata['country'] speakJarv(f"we are in {city} city") except Exception as e: print(e) elif 'take screenshot' in query: speakJarv("Hi, Please tell me the name for the screenshot file") name = listenJarv().lower() speakJarv( "Please hold the screenshot for a moment. i am taking a screenshot" ) time.sleep(3) img = pyautogui.screenshot() img.save(f"{name}.png") speakJarv( "I am done, The screenshot was saved successfully in main folder" )
def save_im(im: Image, save_to: str, im_type: str = "jpeg") -> None: """ Given a PIL image and a directory save the image to the directory; default to jpeg as the image format type. """ im.save(save_to, im_type)
def test_save_failure(self): img = Image(os.path.join(DATADIR, 'test5.gif')) self.assertRaises(errors.ImageSaveError, lambda: img.save(format="webp"))
def image_to_bytes(image: Image) -> io.BytesIO: image_bytes = io.BytesIO() image.save(image_bytes, format="png") image_bytes.seek(0) return image_bytes
def init_image(output_filename): image = Image("RGB", (p.universe_width, p.universe_height), "white") image.save(output_filename)
def upload_pil_image(self, image: Image): output = BytesIO() image.save(output, format="GIF", mode="RGB") return self.upload_image(output.getvalue())
def process_image(self, image:Image) -> bool: has_processed_frame = False if image is None: if include_sample(0.01): print('No frame to write {}:[{}], skipping.'.format( self.config.base_name, self.config.server_uri, )) return has_processed_frame if not include_sample(): return has_processed_frame array = BytesIO() image.save(array, format='PNG') dt = datetime.now() key = 'eufy/{}/{}/{}.png'.format( self.config.base_name, self.config.camera_name, dt.strftime('%Y/%m/%d/%H/%M/%S.%f')) s3_object = S3Object(bucket=self.config.bucket_name, key=key) # Attempt to write the frame try: s3.put_object( Bucket=s3_object.bucket, Key=s3_object.key, Body=array.getvalue(), Metadata={ 'BaseName': self.config.base_name, 'Camera':self.config.camera_name, }) print('Wrote Frame {}: {}'.format(s3_object.s3_uri, image)) # Record that we actually got a valid frame and uploaded it. has_processed_frame = True except Exception as error: print('Unable to write frame: '+str(error)) return has_processed_frame self.__increment_counter("FrameUploaded") # Analyze the frame try: labels = rekclient.detect_s3_labels( s3_object=s3_object) except Exception as error: print('Unable to DetectLabels in {} - {}'.format(s3_object.s3_uri, str(error))) return has_processed_frame self.__increment_counter('BoundedLabelDetected', count=len(labels.bounded_labels)) # Find any faces within the document try: face_document = rekclient.detect_s3_faces( s3_object=s3_object, collection_id=collection_id) for face in face_document.faces: meta = face.summarize(image) meta['S3_Uri'] = s3_object.s3_uri meta['Camera'] = self.config.camera_name meta['BaseName'] =self.config.base_name response = sns.publish( TopicArn=analyzed_frame_topic_arn, Message=dumps(meta,indent=2,sort_keys=True), MessageAttributes={ 'Camera': { 'DataType':'String', 'StringValue':self.config.camera_name }, 'BaseName': { 'DataType':'String', 'StringValue':self.config.base_name }, 'HasPerson': { 'DataType':'String', 'StringValue':'true' }, }) print(response) self.__increment_counter('FaceDetected', count=len(face_document.faces)) except Exception as error: print('Unable to DetectFaces in {} - {}'.format(s3_object.s3_uri, str(error))) return has_processed_frame return has_processed_frame
def convert_to_bytes(self, image: Image) -> bytes: """imageオブジェクトをbyteに変換""" imgByteArr = io.BytesIO() image.save(imgByteArr, format=image.format) return imgByteArr.getvalue()
def savefile(self): r = filedialog.asksaveasfilename(title='savefile', initialdir='./', initialfile='picture.jpg') Image.save(r) print(r)
async def deepfry(img: Image, *, token: str = None, url_base: str = 'westcentralus', session: aiohttp.ClientSession = None, type=DeepfryTypes.RED) -> Image: """ Deepfry an image. img: PIL.Image - Image to deepfry. [token]: str - Token to use for Microsoft facial recognition API. If this is not supplied, lens flares will not be added. [url_base]: str = 'westcentralus' - API base to use. Only needed if your key's region is not `westcentralus`. [session]: aiohttp.ClientSession - Optional session to use with API requests. If provided, may provide a bit more speed. Returns: PIL.Image - Deepfried image. """ img = img.copy().convert('RGB') if type not in DeepfryTypes: raise ValueError( f'Unknown deepfry type "{type}", expected a value from deeppyer.DeepfryTypes' ) if token: req_url = f'https://{url_base}.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=false&returnFaceLandmarks=true' # WHY THE F**K IS THIS SO LONG headers = { 'Content-Type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key': token, 'User-Agent': 'DeepPyer/1.0' } b = BytesIO() img.save(b, 'jpeg') b.seek(0) if session: async with session.post(req_url, headers=headers, data=b.read()) as r: face_data = await r.json() else: async with aiohttp.ClientSession() as s, s.post( req_url, headers=headers, data=b.read()) as r: face_data = await r.json() if 'error' in face_data: err = face_data['error'] code = err.get('code', err.get('statusCode')) msg = err['message'] raise Exception( f'Error with Microsoft Face Recognition API\n{code}: {msg}') if face_data: landmarks = face_data[0]['faceLandmarks'] # Get size and positions of eyes, and generate sizes for the flares eye_left_width = math.ceil(landmarks['eyeLeftInner']['x'] - landmarks['eyeLeftOuter']['x']) eye_left_height = math.ceil(landmarks['eyeLeftBottom']['y'] - landmarks['eyeLeftTop']['y']) eye_left_corner = (landmarks['eyeLeftOuter']['x'], landmarks['eyeLeftTop']['y']) flare_left_size = eye_left_height if eye_left_height > eye_left_width else eye_left_width flare_left_size *= 4 eye_left_corner = tuple( math.floor(x - flare_left_size / 2.5 + 5) for x in eye_left_corner) eye_right_width = math.ceil(landmarks['eyeRightOuter']['x'] - landmarks['eyeRightInner']['x']) eye_right_height = math.ceil(landmarks['eyeRightBottom']['y'] - landmarks['eyeRightTop']['y']) eye_right_corner = (landmarks['eyeRightInner']['x'], landmarks['eyeRightTop']['y']) flare_right_size = eye_right_height if eye_right_height > eye_right_width else eye_right_width flare_right_size *= 4 eye_right_corner = tuple( math.floor(x - flare_right_size / 2.5 + 5) for x in eye_right_corner) # Crush image to hell and back img = img.convert('RGB') width, height = img.width, img.height img = img.resize((int(width**.75), int(height**.75)), resample=Image.LANCZOS) img = img.resize((int(width**.88), int(height**.88)), resample=Image.BILINEAR) img = img.resize((int(width**.9), int(height**.9)), resample=Image.BICUBIC) img = img.resize((width, height), resample=Image.BICUBIC) img = ImageOps.posterize(img, 4) # Generate red and yellow overlay for classic deepfry effect r = img.split()[0] r = ImageEnhance.Contrast(r).enhance(2.0) r = ImageEnhance.Brightness(r).enhance(1.5) if type == DeepfryTypes.RED: r = ImageOps.colorize(r, Colours.RED, Colours.YELLOW) elif type == DeepfryTypes.BLUE: r = ImageOps.colorize(r, Colours.BLUE, Colours.WHITE) # Overlay red and yellow onto main image and sharpen the hell out of it img = Image.blend(img, r, 0.75) img = ImageEnhance.Sharpness(img).enhance(100.0) if token and face_data: # Copy and resize flares flare = Image.open('./deeppyer/flare.png') flare_left = flare.copy().resize((flare_left_size, ) * 2, resample=Image.BILINEAR) flare_right = flare.copy().resize((flare_right_size, ) * 2, resample=Image.BILINEAR) del flare img.paste(flare_left, eye_left_corner, flare_left) img.paste(flare_right, eye_right_corner, flare_right) return img
def image_to_byte_array(image: Image) -> bytes: imgByteArr = io.BytesIO() image.save(imgByteArr, format='png') bytes = imgByteArr.getvalue() return bytes
import os import io import numpy as np import cv2 from PIL import Image from PyQt5 import QtGui # Takes a csv containing RGB565 BMP data and creates a PNG image data = [] # File should be 2x(320x240) = 153600 bytes long infile = open( os.path.expanduser("~/Documents/analyzerdata/greyscale_test_img.csv"), "r+") with infile as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') tmp = '' count = 0 for row in spamreader: data.append(int(', '.join(row), 0)) bmp = bytearray(data) print(len(data)) Image = QtGui.QImage(bmp, 320, 240, QtGui.QImage.Format_RGB16) Image.save("test.png", "PNG", -1)
def generate_image(self, width = 200, height = 70, font_size = 40, vlines = 6, hlines = 10, drawpoints = True, pointdeep = 10, bgcolor = '#eeeeee', linecolor = '#bbbbbb', colors = ['#222222', '#444444', '#666666', '#888888'], pointcolor = '#ffffff'): """ Create a png version of the code image. Arguments: width width in pixel (default: 200) height height in pixel (default: 70) font_size font size in pixel (default: 50) vlines lines crossing the image vertically (default: 6) hlines lines crossing the image horizontally (default: 10) drawpoints should the background of the image be dotted? (default: True) pointdeep number defining amount of dots. (1 - many / 20 - few) if you define a number higher than 20 it's the same is setting drawpoints to False. (default: 10) bgcolor hex value of the background color (default: #eeeeee) linecolor hex value of the line color (default: #bbbbbb) colors list of colors used for the characters pointcolor color of the background dots if enabled (default: #ffffff) """ font_path = os.path.join(os.path.dirname(__file__), 'static', 'captcha.ttf') img = Image('RGB', (width, height), bgcolor) c = Canvas(img) f = Font(font_path, font_size) max_len = len(self.code) # draw background points if drawpoints and pointdeep <= 20: limes = 20 - pointdeep for x in xrange(width): for y in xrange(height): if random.randrange(0, 20) > limes: c.point((x, y), fill=pointcolor) # draw letters for pos, char in enumerate(self.code): color = random.choice(colors) point = (int(width / max_len) * pos + 8, random.randrange(-2, height - font_size - 2)) c.text(point, char, fill=color, font=f) # draw lines for i in xrange(vlines): c.line([(0, random.randrange(0, height + 1)), (width, random.randrange(0, height + 1))], fill=linecolor) for i in xrange(hlines): c.line([(random.randrange(0, width + 1), 0), (random.randrange(0, width + 1), height)], fill=linecolor) out = StringIO() img.save(out, 'PNG') return out.getvalue()
def img_to_byte_arr(image: Image): """convert the test image to bytes array""" img_byte_arr = BytesIO() image.save(img_byte_arr, format='PNG') img_byte_arr = img_byte_arr.getvalue() return img_byte_arr
#Shifting For each Row for i in range(M): R_Total_Sum = sum(R[i]) G_Total_Sum = sum(G[i]) B_Total_Sum = sum(B[i]) R_Mod = R_Total_Sum % 2 G_Mod = G_Total_Sum % 2 B_Mod = B_Total_Sum % 2 if (R_Mod == 0): R[i] = np.roll(R[i], -Kr[i]) else: R[i] = np.roll(R[i], Kr[i]) if (G_Mod == 0): G[i] = np.roll(G[i], -Kr[i]) else: G[i] = np.roll(G[i], Kr[i]) if (B_Mod == 0): B[i] = np.roll(B[i], -Kr[i]) else: B[i] = np.roll(B[i], Kr[i]) for i in range(M): for j in range(N): Pixel[i, j] = (R[i][j], G[i][j], B[i][j]) Image.save('Decrypted_Images/' + sys.argv[1])
def image_to_bytes(image: Image) -> io.BytesIO: with io.BytesIO() as ret: image.save(ret, format='PNG') # return a duplicate of the array because this works for some reason return io.BytesIO(ret.getvalue())
def main(): import sys import tornado.httpclient import tornado.options from tornado.options import define, options, parse_command_line define("operation", help="the operation to be performed", type=str, default="resize", metavar="|".join(["resize", "rotate", "none"])) define("width", help="the desired image width", type=int) define("height", help="the desired image height", type=int) define("mode", help="the resizing mode", metavar="|".join(Image.MODES), type=str) define("background", help="the hexidecimal fill background color", type=str) define("position", help="the crop position", metavar="|".join(Image.POSITIONS), type=str) define("filter", help="default filter to use when resizing", metavar="|".join(Image.FILTERS), type=str) define("degree", help="the desired rotation degree", type=int) define("expand", help="expand image size to accomodate rotation", type=int) define("rect", help="rectangle: x,y,w,h", type=str) define("format", help="default format to use when saving", metavar="|".join(Image.FORMATS), type=str) define("quality", help="default jpeg quality, 0-100", type=int) args = parse_command_line() if not args: print("Missing image source url") sys.exit() elif options.operation == "region": if not options.rect: tornado.options.print_help() sys.exit() elif options.operation == "resize": if not options.width and not options.height: tornado.options.print_help() sys.exit() elif options.operation == "rotate": if not options.degree: tornado.options.print_help() sys.exit() elif options.operation != "noop": tornado.options.print_help() sys.exit() if args[0].startswith("http://") or args[0].startswith("https://"): client = tornado.httpclient.HTTPClient() resp = client.fetch(args[0]) image = Image(resp.buffer) else: image = Image(open(args[0], "r")) if options.operation == "resize": image.resize(options.width, options.height, mode=options.mode, filter=options.filter, background=options.background, position=options.position) elif options.operation == "rotate": image.rotate(options.degree, expand=options.expand) elif options.operation == "region": image.region(options.rect.split(",")) stream = image.save(format=options.format, quality=options.quality) sys.stdout.write(stream.read()) stream.close()
def draw_link( img: Image, ref_box: Box, sample_box: Box, highlights: List[str] = [], highlights_segments: int = 10, result_fn: Optional[str] = None, line_width: int = 5, line_color: Color = (255, 0, 0, 255)) -> Image: """ Draw the link between ref and sample boxes: from left side of ref to right side of sample :param img: coloration :param ref_box: reference box :param sample_box: sample box :param highlights: some of highlight flags : 'ref_top', 'ref_bottom', 'sample_top', 'sample_bottom' :param highlights_segments: number of segments of dashed line :param result_fn: filename for result file save :param line_width: line width (5 by default) :param line_color: line color (red by default) :return: coloration image """ img = img.copy() draw = ImageDraw.Draw(img) # boxes ref_left, ref_upper, ref_right, ref_lower = ref_box sample_left, sample_upper, sample_right, sample_lower = sample_box for i in range(line_width): draw.rectangle( (ref_left + i, ref_upper + i, ref_right - i, ref_lower - i), None, line_color) draw.rectangle((sample_left + i, sample_upper + i, sample_right - i, sample_lower - i), None, line_color) # highlights over the boxes for dashed sides (top and bottom of page) for h in highlights: if h in ('ref_top', 'ref_bottom'): h_left, h_right = ref_left, ref_right else: h_left, h_right = sample_left, sample_right dh_y = line_width // 2 if h == 'ref_top': h_y = ref_upper + dh_y elif h == 'sample_top': h_y = sample_upper + dh_y elif h == 'ref_bottom': h_y = ref_lower - dh_y elif h == 'sample_bottom': h_y = sample_lower - dh_y else: continue segment_width = (h_right - h_left) // (highlights_segments * 2 + 1) bg_color = (255, 255, 255, 255) # white for j in range(1, highlights_segments + 1): segment_right = h_left + 2 * j * segment_width segment_left = segment_right - segment_width begin = segment_left, h_y end = segment_right, h_y draw.line(begin + end, bg_color, line_width + 2) # link begin = ref_left, np.mean([ref_upper, ref_lower]) end = sample_right, np.mean([sample_upper, sample_lower]) draw.line(begin + end, line_color, line_width) # arrow x, y = begin[0] - end[0], begin[1] - end[1] arrow_len = abs(x) // 5 arrow_angle = np.pi / 6 angle = np.arctan2(y, x) up_angle, down_angle = angle + arrow_angle / 2, angle - arrow_angle / 2 up_arrow_end = end[0] + arrow_len * np.cos( up_angle), end[1] + arrow_len * np.sin(up_angle) down_arrow_end = end[0] + arrow_len * np.cos( down_angle), end[1] + arrow_len * np.sin(down_angle) draw.polygon(end + up_arrow_end + down_arrow_end, line_color, line_color) del draw if result_fn is not None: img.save(result_fn) return img
def upload(request): try: image_file = request.FILES['file'] except KeyError: raise PermissionDenied if not validator.name(request.POST.get('name', '')): raise PermissionDenied if not validator.phone(request.POST.get('phone', '')): raise PermissionDenied if not validator.email(request.POST.get('email', '')): raise PermissionDenied if len(request.POST.get('description', '').strip()) == 0: raise PermissionDenied post_name = request.POST['name'].strip() post_phone = request.POST['phone'].strip() post_email = request.POST['email'].strip() post_description = request.POST['description'].strip() try: conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(s3_bucket()) image_key = Image.generate_unique_random_key() data = image_file.read() ext = image_file.name.split(".")[-1].lower() pil_image = PIL.Image.open(StringIO(data)) exif_json = json.dumps(get_exif_tags(pil_image)) image_file_tags = xmp.find_keywords(data) thumbs = [{'size': size, 'data': create_thumb(pil_image, ext, size)} for size in settings.THUMB_SIZES] if pil_image.size[0] < MIN_SIZE or pil_image.size[1] < MIN_SIZE: return HttpResponseBadRequest(json.dumps({ 'files': [{ 'name': image_file.name, 'size': image_file.size, 'error': u"Bildet må være minst 800x800 piksler", }] })) # Give boto an encoded str, not unicode content_type = image_file.content_type.encode('utf-8') key = boto.s3.key.Key(bucket, '%s%s.%s' % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, ext)) key.content_type = content_type key.set_contents_from_string(data, policy='public-read') for thumb in thumbs: key = boto.s3.key.Key(bucket, '%s%s-%s.%s' % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, thumb['size'], ext)) key.content_type = content_type key.set_contents_from_string(thumb['data'], policy='public-read') destination_album = Fotokonkurranse.objects.get().album licence_text = "Kan brukes i DNTs egne kommunikasjonskanaler som magasiner, nettsider og sosiale medier, i PR og for bruk av DNTs sponsorer." image = Image( key=image_key, extension=ext, hash=sha1(data).hexdigest(), description=post_description, album=destination_album, photographer=post_name, credits="%s / DNTs fotokonkurranse" % post_name, licence="%s Kontakt: %s (%s / %s)" % (licence_text, post_name, post_phone, post_email), exif=exif_json, uploader=request.user if not request.user.is_anonymous() else None, width=pil_image.size[0], height=pil_image.size[1]) image.save() for tag in [tag.lower() for tag in image_file_tags]: obj, created = Tag.objects.get_or_create(name=tag) image.tags.add(obj) # Note that we're caching the email address for one hour and not resending the email receipt # for further uploads from that address during this period. if cache.get('fotokonkurranse.emails.%s' % post_email) is None: # Set the cache quickly when we know we're going to send an email. Don't wait until after # it's sent, because other upload requests may try to send meanwhile and we don't want them to. cache.set('fotokonkurranse.emails.%s' % post_email, True, 60 * 60) try: t = loader.get_template('central/fotokonkurranse/email_confirmation.txt') c = RequestContext(request, { 'user_name': post_name, }) send_mail(EMAIL_CONFIRMATION_SUBJECT, t.render(c), settings.DEFAULT_FROM_EMAIL, [post_email]) except (SMTPException, SSLError): cache.delete('fotokonkurranse.emails.%s' % post_email) logger.warning(u"Kvitteringsepost for fotokonkurranse feilet", exc_info=sys.exc_info(), extra={'request': request} ) return HttpResponse(json.dumps({ 'files': [{ 'name': image_file.name, 'size': image_file.size, 'url': '', 'thumbnailUrl': '', 'deleteUrl': '', 'deleteType': '', }] })) except Exception as e: logger.error(u"Feil ved opplasting av bilde til fotokonkurranse", exc_info=sys.exc_info(), extra={'request': request} ) return HttpResponseBadRequest(json.dumps({ 'files': [{ 'name': image_file.name, 'size': image_file.size, 'error': "Exception ved bildeopplasting: %s" % e, }] }))
def write_image(path, Image): Image.save(path);