def save(self, *args, **kwargs): super(Curso, self).save(*args, **kwargs) if not self.id and not self.imagen: return image.resize(image.THUMB, self.imagen)
def save(self, *args, **kwargs): super(Conferencia, self).save(*args, **kwargs) if not self.id and not self.imagen: return image.resize(image.THUMB, self.imagen)
def save(self, *args, **kwargs): super(VideoInvitado, self).save(*args, **kwargs) if not self.id and not self.imagen: return image.resize((100, 100), self.imagen)
def clicked(letter): isLetterFound = False global times for index,let in enumerate(word): #looping to check if the letter exist if letter == let: arry_display[index].config(text = letter) hidden_word[index] = letter isLetterFound = True # If letter was not found, then update the image and increment by one his turn (times) if isLetterFound == False: times +=1 image = Image.open(image_src[times]) image = image.resize((150, 150), Image.ADAPTIVE) imageW = ImageTk.PhotoImage(image) panel.configure(image = imageW) panel.image = imageW if checkIfWin(hidden_word): messagebox.showinfo("Hang man", "Congratulations You win!") window.destroy() if times == 6: image = Image.open(image_src[7]) image = image.resize((150, 150), Image.ADAPTIVE) imageW = ImageTk.PhotoImage(image) panel.configure(image=imageW) panel.image = imageW messagebox.showinfo("Hang man", "Too bad, you lost!")
def save(self, *args, **kwargs): super(Curso, self).save(*args, **kwargs) return if not self.id and not self.imagen: return image.resize((666, 430), self.imagen)
def detect_from_folder(folder, face_cascade): images = fetch_images(folder + "/", "jpg") for image in images: while image.shape[1] > 1024 or image.shape[0] > 786: image.resize( (int(image.shape[1] * 0.9), int(image.shape[0] * 0.9))) image.make_greyscale() image.search_faces(face_cascade) image.detect_faces() if image.display(1000) == False: break cv2.destroyAllWindows()
def run(self, img, iterations, step_size, octave, octave_scale, max_loss=None): """ Runs CreepDream Runs gradient ascent. First it upscales provided image to particular scale then it reinjects the detail that was lost at upscaling time back. Parameters ---------- img : ndarray Image as a numpy array iterations : int Number of iterations step_size : int Gradient ascent step size octave : int Number of scales at which to run gradient ascent octave_scale : float Size ratio between shapes max_loss : float Gradient descent max loss Returns ------- img : ndarray Deep dream modified image """ # create image shapes of different sizes shapes = self._shapes(img, octave, octave_scale) # copy original image - we want to avoid modifying it orig_img = np.copy(img) shrunk_orig_img = resize(img, shapes[0]) for shape in shapes: img = resize(img, shape) img = self._gradient_ascent(img, iterations=iterations, step_size=step_size, max_loss=max_loss) # upscale shrunk image: not in first iteration this will do nothing upscaled_shrunk_orig_img = resize(shrunk_orig_img, shape) # upscale original image: from the original size back to original same_size_orig_img = resize(orig_img, shape) lost_detail = same_size_orig_img - upscaled_shrunk_orig_img img += lost_detail shrunk_orig_img = resize(orig_img, shape) return img
def uploadNoInput(req): data.clearDatabase() lastID = data.writeDatabase("auto", "*****@*****.**", "auto", "auto") last = data.getEntryFromID(lastID) obj = "" fileitem = req.form['file'] if fileitem.filename: # strip leading path from file name to avoid directory traversal attacks # also prepend DB ID so filenames are unique fname = str(last['_id'])+"_"+os.path.basename(fileitem.filename) obj = data.updateFilenameFromID(last['_id'],fname) # build absolute path to files directory dir_path = os.path.join(os.path.dirname(req.filename), 'files') open(os.path.join(dir_path, fname), 'wb').write(fileitem.file.read()) #obj = analyze.histogram(last['_id']) obj = image.resize(last['_id']) obj = analyze.histogram(last['_id'], 4) message = "<HTML>" message += 'The file "%s" was uploaded, resized, and analyzed successfully' % fname #message += 'go <a href="#" onClick = "history.back()"> back </a> message += '\n<img src="'+cfg.imageWebPath+fname+'">' f = open("/srv/www/htdocs/lighting/app/control.html",'r') message += f.read() #message += '<br>debug of DB object: <br>' #for x in obj: # message +=(x+": "+str(obj[x])+"<br>") #message += "<p>" #message += "</HTML>" else: message = 'No file was uploaded' return message
async def resize_remote(url: str = 'https://s.gravatar.com/avatar/434d67e1ebc4109956d035077ef5adb8', height: int = 250, width: int = 250, image_format: str = 'JPEG', resample: Optional[int] = 1): """ Resizes image at URL specified to the specified output resolution and format. * `url` specifies the image URL. * The variables `width` and `height` specify the width and height of the output resize. * The `image_format` variable can be any output format supported by Pillow. See here: https://tinyurl.com/yymmmpwk * Variable `resample` is used to specify the resample mode used by Pillow. See here: https://tinyurl.com/y3jo6aph * `Image.NEAREST = 0` * `Image.LANCZOS = 1` * `Image.BILINEAR = 2` * `Image.BICUBIC = 3` * `Image.BOX = 4` * `Image.HAMMING = 5` * Output is a an image file. Defaults to JPEG. """ response = requests.get(url) if response.status_code != 200: raise HTTPException(status_code=response.status_code, detail=f'Server returned error {response.status_code}.') if len(response.content) > 20971520: raise HTTPException(status_code=413, detail="Content is too large.") content = BytesIO(response.content) content.seek(0) image_buffer = resize(content, width, height, image_format, resample) content.close() return Response(image_buffer.getvalue(), status_code=200)
def uploadAndInput(req, name, email, title, comment): data.clearDatabase() lastID = data.writeDatabase(name, email, title, comment) last = data.getEntryFromID(lastID) obj = "" fileitem = req.form['file'] if fileitem.filename: # strip leading path from file name to avoid directory traversal attacks # also prepend DB ID so filenames are unique fname = str(last['_id'])+"_"+os.path.basename(fileitem.filename) obj = data.updateFilenameFromID(last['_id'],fname) # build absolute path to files directory dir_path = os.path.join(os.path.dirname(req.filename), 'files') open(os.path.join(dir_path, fname), 'wb').write(fileitem.file.read()) #obj = analyze.histogram(last['_id']) obj = image.resize(last['_id']) obj = analyze.histogram(last['_id'], 4) message = "<HTML>" message += 'The file "%s" was uploaded, resized, and analyzed successfully' % fname message += '\n<img src="'+cfg.imageWebPath+fname+'">' message += '<br>debug of DB object: <br>' for x in obj: message +=(x+": "+str(obj[x])+"<br>") message += "<p>" message += "</HTML>" else: message = 'No file was uploaded' return message
async def resize_local(data: ResizeImage): """ Resizes incoming base64 image. * `b64_image` is the base64 image of any supported format. See here for supported inputs: https://tinyurl.com/yymmmpwk * The variables `width` and `height` specify the width and height of the output resize. * The `image_format` variable can be any output format supported by Pillow. See here: https://tinyurl.com/yymmmpwk * Variable `resample` is used to specify the resample mode used by Pillow. See here: https://tinyurl.com/y3jo6aph * `Image.NEAREST = 0` * `Image.LANCZOS = 1` * `Image.BILINEAR = 2` * `Image.BICUBIC = 3` * `Image.BOX = 4` * `Image.HAMMING = 5` * Output is a an image file. Defaults to JPEG. """ b64_image = data.get('base64_image') if get_b64_size(b64_image) > 20971520: raise HTTPException(status_code=413, detail="Content is too large.") image_format = data.get('image_format') width = data.get('width') height = data.get('height') resample = data.get('resample') content = BytesIO(base64.b64decode(b64_image)) content.seek(0) image_buffer = resize(content, width, height, image_format, resample) content.close() return Response(image_buffer.getvalue(), status_code=200)
def upload(req): fileitem = req.form['file'] accepted = ['jpg', 'png', 'gif'] if fileitem.filename: extension = os.path.splitext(fileitem.filename)[1][1:] # ensure it's an image… if (extension.lower() in accepted): # strip leading path from file name to avoid directory traversal attacks # also prepend DB ID so filenames are unique fname = os.path.basename(fileitem.filename) # build absolute path to files directory dir_path = os.path.join(os.path.dirname(req.filename), 'files') open(os.path.join(dir_path, fname), 'wb').write(fileitem.file.read()) obj = image.resize(fname) message = '<html>The file "%s" was uploaded successfully' % fname message += '<br/>Please copy the following, and paste in the text box after hitting <back> button' message += '<textarea rows="4" cols="50"><img src="' + cfg.imageWebPath + fname + '"/></textarea>' message += '</html>' else: message = 'No file was uploaded - only jpeg, gif, or png accepted' return message
def upload(req): fileitem = req.form['file'] accepted = ['jpg', 'png', 'gif'] if fileitem.filename: extension = os.path.splitext(fileitem.filename)[1][1:] # ensure it's an image… if (extension.lower() in accepted): # strip leading path from file name to avoid directory traversal attacks # also prepend DB ID so filenames are unique fname = os.path.basename(fileitem.filename) # build absolute path to files directory dir_path = os.path.join(os.path.dirname(req.filename), 'files') open(os.path.join(dir_path, fname), 'wb').write(fileitem.file.read()) obj = image.resize(fname) message = '<html>The file "%s" was uploaded successfully' % fname message += '<br/>Please copy the following, and paste in the text box after hitting <back> button' message += '<textarea rows="4" cols="50"><img src="'+cfg.imageWebPath+fname+'"/></textarea>' message += '</html>' else: message = 'No file was uploaded - only jpeg, gif, or png accepted' return message
def sample(index): if index < 0: return flask.make_response('index cannot be negative', 404) if index >= len(app.config['sample_offsets']): return flask.make_response('index cannot be larger than amount of images', 404) sample_offset = app.config['sample_offsets'][index] with app.config['input_samples_file_lock']: input_samples_file = app.config['arguments']['input_samples_file'] input_samples_file.seek(sample_offset[0]) data_bytes = input_samples_file.read(sample_offset[1]) computed_masked_crc32_of_data = masked_crc32c(data_bytes) masked_crc32_of_data_bytes = input_samples_file.read(4) masked_crc32_of_data = struct.unpack( '<L', masked_crc32_of_data_bytes)[0] if masked_crc32_of_data != computed_masked_crc32_of_data: raise RuntimeError( f'CRC integrity check failed for data in input samples file at {sample_offset[0]}') example = viewer.example_pb2.Example() example.ParseFromString(data_bytes) data_shape_feature = example.features.feature['dataShape'] assert data_shape_feature.HasField('int64_list') data_shape = data_shape_feature.int64_list.value data_feature = example.features.feature['data'] assert data_feature.HasField('int64_list') data = np.reshape( np.array(data_feature.int64_list.value, dtype=np.uint8), tuple(data_shape)) image = np.repeat(data, repeats=3, axis=2) if 'scale' in flask.request.args: try: scale_width = int( flask.request.args['width']) if 'width' in flask.request.args else None scale_height = int( flask.request.args['height']) if 'height' in flask.request.args else None except ValueError: return flask.make_response('width or height malformed', 404) if scale_width is None and scale_height is None: return flask.make_response('width and height missing', 404) if scale_width is None: scale_width = int(scale_height / image.shape[0] * image.shape[1]) if scale_height is None: scale_height = int(scale_width / image.shape[1] * image.shape[0]) size = np.array([[scale_width], [scale_height]]) image = img.resize(image, size) response = flask.make_response(img.encode(image, 'png')) response.headers['Content-Type'] = 'image/png' return response
def regenerate(solicitud): for video in Video.objects.all(): image.resize(image.THUMB, video.imagen) image.resize(image.SINGLE, video.imagen) image.resize(image.HOME, video.imagen) for curso in Curso.objects.all(): image.resize(image.THUMB, curso.imagen) return redirect('/')
def detect(im, cascade, haar_scale=1.2, min_neighbors=2, min_size=(20,20)): haar_flags = 0 gray = image.rgb2gray(im) small = image.resize(gray, by_percent=im_scale) cv.EqualizeHist(small, small) objs = cv.HaarDetectObjects(small, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, cv.CV_HAAR_DO_CANNY_PRUNING, min_size) return [Rect(r,n,cv.GetSize(im)) for r,n in objs]
def save(self, *args, **kwargs): super(Video, self).save(*args, **kwargs) if not self.id and not self.imagen: return image.resize(image.THUMB, self.imagen) image.resize(image.SINGLE, self.imagen) image.resize(image.HOME, self.imagen)
def get_resized_image(size, filename): w, h = size.split("x") _, ext = filename.split(".") filename_with_size = "{}_{}x{}.jpg".format(filename, w, h) file_path = bucket.download(filename_with_size) if file_path: return send_file(file_path, mimetype='image/{}'.format(ext)) file_path = bucket.download(filename) if not file_path: return abort(404) resized_file_path = image.resize(file_path, (int(w), int(h))) bucket.upload(resized_file_path, filename) return send_file(resized_file_path, mimetype='image/{}'.format(ext))
def preprocess(self, request): """ Decode all input images into numpy array. Note: This implementation doesn't properly handle error cases in batch mode, If one of the input images is corrupted, all requests in the batch will fail. :param request: :return: """ img_list = [] param_name = self.signature['inputs'][0]['data_name'] input_shape = self.signature['inputs'][0]['data_shape'] for idx, data in enumerate(request): img = data.get(param_name) if img is None: img = data.get("body") if img is None: img = data.get("data") if img is None or len(img) == 0: self.error = "Empty image input" return None # We are assuming input shape is NHWC [h, w] = input_shape[1:3] try: img_arr = image.read(img) except Exception as e: logging.warn(e, exc_info=True) self.error = "Corrupted image input" return None img_arr = image.resize(img_arr, w, h) img_arr = image.transform_shape(img_arr) img_list.append(img_arr) #Convert to dict before returning [{name: image}] img_list = [{param_name: img} for img in img_list] return img_list
def resizeImage(image, size): widthDev, heightDev = size widthImg, heightImg = image.size if widthImg <= widthDev and heightImg <= heightDev: return image ratioImg = float(widthImg) / float(heightImg) ratioWidth = float(widthImg) / float(widthDev) ratioHeight = float(heightImg) / float(heightDev) if ratioWidth > ratioHeight: widthImg = widthDev heightImg = int(widthDev / ratioImg) elif ratioWidth < ratioHeight: heightImg = heightDev widthImg = int(heightDev * ratioImg) else: widthImg, heightImg = size return image.resize((widthImg, heightImg), Image.ANTIALIAS)
def resize_image(data, resize_ratio=image.DEFAULT_RATIO): return base64.encode(image.resize(base64.b64decode(data)))
def preprocess(listofimages, inputsize, mean, std, dimorder='chw', channelorder='rgb', scale=1.0): """ Preprocess a list of images to be used with the neural network. Automatically loads images from disk if a string is given. Parameters ---------- listofimages : List of strings or list of unprocessed ndarrays, shape (Height, Width, Channels) The list may contain image filepaths and image ndarrays. ndarrays have to be in range between 0 and 1. inputsize : tuple or list Target input data dimensionality of same format as dimorder mean : ndarray Image mean definition of format (channels, height, width) or (channels, ). Set to None, to ignore. std : ndarray Standard deviation definition of format (channels, height, width) or (channels, ) Set to None, to ignore dimorder : string Order of dimensions. Default chw (channel, height, width) channelorder : string Order of color channels. Default: rgb (red, green, blue) scale : float Scaling of color values. Returns ------- output : ndarray Preprocessed batch of images ready for the forward pass. """ # Convert dimorder to tuple dimmap = { 'h': 0, 'w': 1, 'c': 2, } imsize = (inputsize[dimorder.find('h')], inputsize[dimorder.find('w')]) dimorder = [dimmap[c] for c in dimorder] # Load data in first step from list data = np.zeros( (len(listofimages), inputsize[0], inputsize[1], inputsize[2]), dtype=np.float32) for i, h in enumerate(listofimages): if type(h) is str: im = image.read(h) elif type(h) is np.ndarray: im = h.copy() if im.shape[:2] != imsize: im = image.resize(im, imsize) if scale != 1.0: im *= scale if mean is not None and mean.ndim == 1: im -= mean if std is not None and std.ndim == 1: im /= std if channelorder == 'bgr': im = im[:, :, ::-1] im = im.transpose( *dimorder) # resulting order is: channels x height x width if mean is not None and mean.ndim == 3: im -= mean if std is not None and std.ndim == 3: im /= std data[i] = im return data
def main(progname, *args): parser = OptionParser() parser.add_option("-f", "--file", dest="filename", default=None, help="analyze a given FILE ending in .jpg or .jpeg", metavar="FILE") parser.add_option("-i", "--imageset", dest="imageset", default=None, help="Runs on a predefined set of algorithms (li,chow,china,custom)") parser.add_option("-d", "--debug", dest="debug", action="store_true", default=False, help="Enable visual debugging.") parser.add_option("-t", "--type", dest="type", default="all", help="Specifies the type of feature to debug. Defaults to all.") (options, args) = parser.parse_args(list(args)) if options.imageset: if options.imageset == 'li': process(li_dir) return 0 elif options.imageset == 'chow': process(chow_dir) return 0 elif options.imageset == 'china': process(china_dir) return 0 elif options.imageset == 'custom': process() return 0 if not options.filename: print "Please specify a file (--file) or image set (--imageset)." return 1 if not options.debug: process([load_image(options.filename)]) return 0 if options.filename.startswith('data/'): options.filename = options.filename[len('data/'):] tdata = load_image(options.filename) kind = options.type.lower() size = None #(320,240,'crop') # (0.5, 0.5, 'resize-p') if size is None: im = tdata.load() elif size[-1] == 'crop': im = image.random_cropped_region(tdata.load(), size[:2]) elif size[-1] == 'resize': im = tdata.load(size[:2]) elif size[-1] == 'resize-p': im = image.resize(tdata.load(), by_percent=size[:2]) else: raise TypeError, "Invalid image sizing type." image.show(im, "Image") #l,u,v = image.split(image.rgb2luv(im)) ##cv.Set(l, 128) ##cv.EqualizeHist(l, l) ##cv.EqualizeHist(u, u) ##image.show(image.luv2rgb(image.merge(l,u,v)), "test") #s = cv.GetSize(im) #t = image.absDiff(u,v) #image.show(t, "test") #print "Test Score:", cv.CountNonZero(t) / float(s[0] * s[1]) ##image.show(image.threshold(image.And(u,v), threshold=1), "LUV") # noise if kind in ('all','noise'): noise_img, score = noise.measure(im, debug=True) #image.show(noise_img, "Noise Result") print 'Noise Score:', score, noise.boolean(score) # contrast if kind in ('all','contrast'): contrast_img, score = contrast.measure(im, debug=True) #image.show(contrast_img, "Contrast Result") print 'Contrast Score:', score, contrast.boolean(score) # blur if kind in ('all','blur','composition'): focused, score = blur.measure(im, debug=kind in ('all','blur')) #image.show(focused, "Blur Result") print 'Blur Score:', score, blur.boolean(score) # composition if kind in ('all','composition'): composition_img, score = composition.measure(im, (focused,score, blur.boolean(score)), debug=True) print 'Composition Score:', score, composition.boolean(score) if kind in ('faces',): result, score = faces.measure(im,debug=True) print "Face Score:", score, faces.boolean(faces) #win = CornerTweaker(im) #win.show() #_, sat, _ = image.split(image.rgb2hsv(im)) #arr = image.cv2array(sat) #print arr.mean(), arr.std() # faces #im, score = faces.measure(im, debug=True) #print score, faces.boolean(score) # composition #noise_img, score = noise.measure(im, debug=False) ##n = (noise_img, score, noise.boolean(score)) #hulls, score = blur.measure(im, debug=False) #b = (hulls, score, blur.boolean(score)) #cimg, score = composition.measure(im, b, debug=True) #print score, composition.boolean(score) # BLUR #from time import time #start = time() ##im2 = image.threshold(image.laplace(im), threshold=75, type=cv.CV_THRESH_TOZERO) #hulls, score = blur.measure(im, debug=True) ##blur_img, score = blur.measure(im, debug=True) #end = time() #print "Time:", (end - start), "seconds" #image.show(im, "image") ##image.show(noise_img, "Noise Image") #print score, blur.boolean(score) #CONTRAST #_, score = contrast.measure(im, debug=True) #image.show(im, "Image") #print score, contrast.boolean(score) """ #BLUR #im2 = image.threshold(image.laplace(im), threshold=75, type=cv.CV_THRESH_TOZERO) im3, score = blur.measure(im, debug=True) image.show(im, "image") image.show(im3, "Focus Mask") print score, blur.boolean(score) #plt.show() """ #NOISE #noise_img, score = noise.measure(im, debug=True) #image.show(noise_img, "Noise") #print score, noise.boolean(score) """ #hwin = ColorHistograms(im) #hwin.show() hwin = HistogramWindow(image.rgb2gray(im)) hwin.show() print cv.GetSize(im), cv.GetSize(im2) print 'blur', papers.blurry_histogram(im) #print papers.blurry_histogram(im2) wind = DerivativeTweaker(im, title="image derivative") wind.show() win = EdgeThresholdTweaker(im, title="image edges") win.show(50)#edge_threshold(im)) #win2 = EdgeThresholdTweaker(im2, title="image resized edges") #win2.show(edge_threshold(im2)) """ cv.WaitKey() cv.DestroyAllWindows() return 0
from image import load_image, resize from facial import facecrop import cv2 import numpy as np a = lambda *k: np.array(k) jeff = load_image('jeff.jpg') jeff = facecrop(jeff) jeff = resize(jeff, 512) height, width = jeff.shape[0:2] bw = jeff[:, :, 1:2] bw = cv2.equalizeHist(bw) # lowpass from cv2tools import vis, filt fbw = np.divide(bw, 255, dtype='float32') # lp = vis.lanczos_filter(fbw, 2,2, a=2) lp = vis.lanczos_filter(fbw**2.2, 2, 2, a=2) c = np.full_like(jeff, 255) def italic_iteration(refimg, callback, angle=25, step=4.0, vstep=4.0): # signature for callback: (x, y, linebegin=False) t = theta = angle / 180 * np.pi xf = a([np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)])
def stretchImage(image, size): widthDev, heightDev = size return image.resize((widthDev, heightDev), Image.ANTIALIAS)
def main(progname, *args): parser = OptionParser() parser.add_option("-f", "--file", dest="filename", default=None, help="analyze a given FILE ending in .jpg or .jpeg", metavar="FILE") parser.add_option( "-i", "--imageset", dest="imageset", default=None, help="Runs on a predefined set of algorithms (li,chow,china,custom)") parser.add_option("-d", "--debug", dest="debug", action="store_true", default=False, help="Enable visual debugging.") parser.add_option( "-t", "--type", dest="type", default="all", help="Specifies the type of feature to debug. Defaults to all.") (options, args) = parser.parse_args(list(args)) if options.imageset: if options.imageset == 'li': process(li_dir) return 0 elif options.imageset == 'chow': process(chow_dir) return 0 elif options.imageset == 'china': process(china_dir) return 0 elif options.imageset == 'custom': process() return 0 if not options.filename: print "Please specify a file (--file) or image set (--imageset)." return 1 if not options.debug: process([load_image(options.filename)]) return 0 if options.filename.startswith('data/'): options.filename = options.filename[len('data/'):] tdata = load_image(options.filename) kind = options.type.lower() size = None #(320,240,'crop') # (0.5, 0.5, 'resize-p') if size is None: im = tdata.load() elif size[-1] == 'crop': im = image.random_cropped_region(tdata.load(), size[:2]) elif size[-1] == 'resize': im = tdata.load(size[:2]) elif size[-1] == 'resize-p': im = image.resize(tdata.load(), by_percent=size[:2]) else: raise TypeError, "Invalid image sizing type." image.show(im, "Image") #l,u,v = image.split(image.rgb2luv(im)) ##cv.Set(l, 128) ##cv.EqualizeHist(l, l) ##cv.EqualizeHist(u, u) ##image.show(image.luv2rgb(image.merge(l,u,v)), "test") #s = cv.GetSize(im) #t = image.absDiff(u,v) #image.show(t, "test") #print "Test Score:", cv.CountNonZero(t) / float(s[0] * s[1]) ##image.show(image.threshold(image.And(u,v), threshold=1), "LUV") # noise if kind in ('all', 'noise'): noise_img, score = noise.measure(im, debug=True) #image.show(noise_img, "Noise Result") print 'Noise Score:', score, noise.boolean(score) # contrast if kind in ('all', 'contrast'): contrast_img, score = contrast.measure(im, debug=True) #image.show(contrast_img, "Contrast Result") print 'Contrast Score:', score, contrast.boolean(score) # blur if kind in ('all', 'blur', 'composition'): focused, score = blur.measure(im, debug=kind in ('all', 'blur')) #image.show(focused, "Blur Result") print 'Blur Score:', score, blur.boolean(score) # composition if kind in ('all', 'composition'): composition_img, score = composition.measure( im, (focused, score, blur.boolean(score)), debug=True) print 'Composition Score:', score, composition.boolean(score) if kind in ('faces', ): result, score = faces.measure(im, debug=True) print "Face Score:", score, faces.boolean(faces) #win = CornerTweaker(im) #win.show() #_, sat, _ = image.split(image.rgb2hsv(im)) #arr = image.cv2array(sat) #print arr.mean(), arr.std() # faces #im, score = faces.measure(im, debug=True) #print score, faces.boolean(score) # composition #noise_img, score = noise.measure(im, debug=False) ##n = (noise_img, score, noise.boolean(score)) #hulls, score = blur.measure(im, debug=False) #b = (hulls, score, blur.boolean(score)) #cimg, score = composition.measure(im, b, debug=True) #print score, composition.boolean(score) # BLUR #from time import time #start = time() ##im2 = image.threshold(image.laplace(im), threshold=75, type=cv.CV_THRESH_TOZERO) #hulls, score = blur.measure(im, debug=True) ##blur_img, score = blur.measure(im, debug=True) #end = time() #print "Time:", (end - start), "seconds" #image.show(im, "image") ##image.show(noise_img, "Noise Image") #print score, blur.boolean(score) #CONTRAST #_, score = contrast.measure(im, debug=True) #image.show(im, "Image") #print score, contrast.boolean(score) """ #BLUR #im2 = image.threshold(image.laplace(im), threshold=75, type=cv.CV_THRESH_TOZERO) im3, score = blur.measure(im, debug=True) image.show(im, "image") image.show(im3, "Focus Mask") print score, blur.boolean(score) #plt.show() """ #NOISE #noise_img, score = noise.measure(im, debug=True) #image.show(noise_img, "Noise") #print score, noise.boolean(score) """ #hwin = ColorHistograms(im) #hwin.show() hwin = HistogramWindow(image.rgb2gray(im)) hwin.show() print cv.GetSize(im), cv.GetSize(im2) print 'blur', papers.blurry_histogram(im) #print papers.blurry_histogram(im2) wind = DerivativeTweaker(im, title="image derivative") wind.show() win = EdgeThresholdTweaker(im, title="image edges") win.show(50)#edge_threshold(im)) #win2 = EdgeThresholdTweaker(im2, title="image resized edges") #win2.show(edge_threshold(im2)) """ cv.WaitKey() cv.DestroyAllWindows() return 0
def load_reference_image(self, path): loaded = load_image(path) loaded = artistic_enhance(loaded) loaded = resize(loaded, self.pixelsize) loaded = np.clip(loaded * 255, 0, 255) self.set_reference_image(loaded.astype('uint8'))
shellRecipe2 = recipe2['shell']['recipe'] # creating a variable for recipe 3, a string that will be the title of the recipe, pulling info from the recipe index recipe3String = recipe3['base_layer']['name'] + ' with ' + recipe3['mixin'][ 'name'] + ' and ' + recipe3['condiment']['name'] # creating variables that will contain the recipe for each part of the taco, grabbing positions from the json data keys seasoningRecipe3 = recipe3['seasoning']['recipe'] condimentRecipe3 = recipe3['condiment']['recipe'] mixinRecipe3 = recipe3['mixin']['recipe'] base_layerRecipe3 = recipe3['base_layer']['recipe'] shellRecipe3 = recipe3['shell']['recipe'] # the following image processes use the pillow library # creating a variable to open the taco pic, resizing the pic, then saving the resized pic image = Image.open('tacopic.jpg') image = image.resize((400, 400)) image.save('tacopic.jpg') # opening the taco pic again, using the ImageDraw to write on the picture, setting the font, font size, color, and location of the text, then saving the edited pic image = Image.open('tacopic.jpg') imgDraw = ImageDraw.Draw(image) font = ImageFont.truetype('DejaVuSans.ttf', 20) imgDraw.text([0, 350], 'Random Taco Cookbook', fill='black', font=font) image.save('tacopic2.jpg') # creating a new word document using the docx library document = docx.Document() # adding a heading (title), on the first line, and setting the font size newHeading = document.add_heading(level=0) writeHeading = newHeading.add_run('Random Taco Cookbook') writeHeading.font.size = Pt(24)
if __name__ == "__main__": path = [] if len(sys.argv) > 1: for i in range(1, len(sys.argv)): path.append(sys.argv[i]) else: # path = ["p1.jpg", "p2.jpg"] # path = ["p1.jpg", "p2.jpg", "p3.jpg"] path = ["p1.jpg", "p2.jpg", "p3.jpg", "p4.jpg"] images = [] for p in path: raw = cv2.imread(p) images.append(Image(resize(raw))) result = images[0].raw for i in range(1,len(images)): img1 = Image(result) img2 = images[i] visualizeMatch(img1, img2) M = transform(img1, img2) # print(M) warpImg = cv2.warpPerspective(img2.raw, np.linalg.inv(M), (img1.raw.shape[1]+img2.raw.shape[1], img1.raw.shape[0])) result = stitch(img1.raw, warpImg) cv2.imshow("Panorama", result) cv2.waitKey(0) cv2.imwrite("result.jpg", result)
def save(self, *args, **kwargs): super(CursoDocente, self).save(*args, **kwargs) if not self.id and not self.imagen: return image.resize((67, 67), self.imagen)
thickness=8, lineType=cv2.LINE_AA, shift=0, ) def blurit(map): blur_r = int(map.shape[0] / 35) for i in range(3): map = cv2.blur(map, (blur_r, blur_r)) map.shape += 1, return map map = blurit(map) return np.divide(map, 255, dtype='float32') if __name__ == '__main__': jeff = load_image('jeff.jpg') jeff = facecrop(jeff) jeff = resize(jeff, 256) map = heatmap(jeff) cv2.imshow('jeff', jeff) cv2.imshow('map', map) cv2.imshow('blended', (jeff * map).astype('uint8')) cv2.waitKey(0)
def refresh_image(self): img = self._project.get_image_paint(self._current_dataset,self._selectedItem,self._selectedContour) qim = to_qt(resize(img,(780,480))) pix = QtGui.QPixmap.fromImage(qim) self.imgLbl.setPixmap(pix)
def getEmail(): detach_dir = cfg.emailImagePath # directory where to save attachments user = cfg.emailUser pwd = cfg.emailPass # connecting to the gmail imap server m = imaplib.IMAP4_SSL("imap.gmail.com") m.login(user,pwd) m.select(cfg.emailLabel) # here you a can choose a mail box like INBOX instead # use m.list() to get all the mailboxes #print m.list() resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp) #resp, items = m.search(None, '(FROM "ucla.edu")') authorName = "" authorEmail = "" authorTitle = "" authorDescription = "" items = items[0].split() if(items): for emailid in items: resp, data = m.fetch(emailid, "(RFC822)") #"`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object #Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue #print mail["From"] +":" + mail["Subject"] authorTitle = mail["Subject"] authorName = mail["From"].split('<',2)[0] #print authorName authorEmail = mail["From"].split('<',2)[1].rstrip(">") #print authorEmail for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue if part.get_content_maintype() == 'text': message = part.get_payload() #print "body :"+ message authorDescription = message #print "Name :"+ authorName #print "eMail:"+ authorEmail #print "title:"+authorTitle #print "desc :"+ authorDescription continue # is this part an attachment ? if part.get('Content-Disposition') is None: continue filename = part.get_filename() counter = 1 # if there is no filename, we create one with a counter to avoid duplicates if not filename: filename = 'part-%03d%s' % (counter, 'bin') counter += 1 att_path = os.path.join(detach_dir, authorEmail+"_"+filename) #Check if its already in the email directory if not os.path.isfile(att_path) : # new data, save info to database lastID = db.writeDatabase(authorName, authorEmail,authorTitle, authorDescription) last = db.getEntryFromID(lastID) #write to normal image directory w/ UID prefix imgPath = os.path.join(cfg.imageFilePath, str(last['_id'])+"_"+filename) obj = db.updateFilenameFromID(last['_id'],str(last['_id'])+"_"+filename) eImgPath = os.path.join(cfg.emailImagePath, authorEmail+"_"+filename) # write to email image directory, so we don't re-insert same image later fp = open(eImgPath, 'wb') fp.write(part.get_payload(decode=True)) fp.close() fp = open(imgPath, 'wb') fp.write(part.get_payload(decode=True)) fp.close() obj = img.resize(last['_id']) obj = analyze.histogram(last['_id'], cfg.analysisMode)
def image(index): if index < 0: return flask.make_response('index cannot be negative', 404) if index >= len(app.config['annotations'].keys()): return flask.make_response('index cannot be larger than amount of images', 404) image = sorted(app.config['annotations'].keys())[index] image = img.read(image) image = img.convert_color_space( image, source_color_space=app.config['arguments']['color_space'], target_color_space='RGB', ) if 'crop' in flask.request.args: try: center_x = float(flask.request.args['centerX']) center_y = float(flask.request.args['centerY']) radius = float(flask.request.args['radius']) except (KeyError, ValueError): return flask.make_response('centerX, centerY, or radius missing or malformed', 404) upper_left = np.array([[center_x - radius], [center_y - radius]]) lower_right = np.array([[center_x + radius], [center_y + radius]]) image = img.crop( image, upper_left, lower_right, [ app.config['arguments']['default_gray'], app.config['arguments']['default_gray'], app.config['arguments']['default_gray'], ], ) if 'scale' in flask.request.args: try: scale_width = int( flask.request.args['width']) if 'width' in flask.request.args else None scale_height = int( flask.request.args['height']) if 'height' in flask.request.args else None except ValueError: return flask.make_response('width or height malformed', 404) if scale_width is None and scale_height is None: return flask.make_response('width and height missing', 404) if scale_width is None: scale_width = int(scale_height / image.shape[0] * image.shape[1]) if scale_height is None: scale_height = int(scale_width / image.shape[1] * image.shape[0]) size = np.array([[scale_width], [scale_height]]) image = img.resize(image, size) response = flask.make_response(img.encode(image, 'png')) response.headers['Content-Type'] = 'image/png' return response
def loadImage(self, filename, resize=None): image = Image.open(filename) if resize is not None: image = image.resize(resize, Image.ANTIALIAS) return ImageTk.PhotoImage(image)