def get_average_colour(image_name, colour_list, frame_folder): image = Image.open(frame_folder + "/" + image_name) average = ImageStat.Stat(image).mean colour_list.append(average)
torch.backends.cudnn.benchmark = True imgs = os.listdir(opt.inp) for img in imgs: start_time = time.time() print(f"Handling with {img}") img_path = os.path.join(opt.inp, img) data = Image.open(img_path).convert('L') size_origin = data.size data = data.resize((512, 512)) w, h = data.size[0], data.size[1] pw = 8 - (w % 8) if w % 8 != 0 else 0 ph = 8 - (h % 8) if h % 8 != 0 else 0 stat = ImageStat.Stat(data) data = ((transforms.ToTensor()(data) - immean) / imstd).unsqueeze(0) if pw != 0 or ph != 0: data = torch.nn.ReplicationPad2d((0, pw, 0, ph))(data).data #start_time = time.time() if use_cuda: pred = model.cuda().forward(data.cuda()).float() else: pred = model.forward(data) #print('elapse time is {}'.format(time.time() - start_time)) pred = F.interpolate(pred, size_origin) out_path = os.path.join(opt.outp, img) save_image(pred[0], out_path) print(f"time consumed: {time.time() - start_time}")
def brightness( im_file ): im = Image.open(im_file) stat = ImageStat.Stat(im) bright = stat.rms[0] return bright
def process(self, element): """Process an image. Use the image id to read the image from Google cloud storage, process the image, then return item_id and the generated image features. Args: element: the element being processed Returns: The processed element. """ item_id, image_id = element[0], element[1] if not image_id: self.missing_image_counter.inc() return # image_uri = "gs://avito-kaggle/train_jpg/%s.jpg" %image_id image_uri = "gs://avito-kaggle/test_jpg/%s.jpg" % image_id try: with file_io.FileIO(image_uri, mode='rb') as f: # with gcs.open(image_uri) as f: image_bytes = f.read() img = Image.open(io.BytesIO(image_bytes)) # A variety of different calling libraries throw different exceptions here. # They all correspond to an unreadable file so we treat them equivalently. except Exception as e: # pylint: disable=broad-except logging.exception('Error processing image %s: %s', image_uri, str(e)) self.error_processing_image_counter.inc() return # local test. # archive = zipfile.ZipFile('data/train_jpg.zip', 'r') # image_file = 'data/competition_files/train_jpg/%s.jpg' %image_id # try: # with archive.open(image_file) as f: # image_bytes = f.read() # img = Image.open(io.BytesIO(image_bytes)) # except Exception as e: # pylint: disable=broad-except # logging.exception('Error processing image %s: %s', image_id, str(e)) # return # Count number of image processed. self.image_counter.inc() # Simple pixel size feature width, height = img.size img_yuv = img.convert('YCbCr') #min, max, avg, std of luminance luminance_min, luminance_max = ImageStat.Stat(img_yuv).extrema[0] luminance_avg = ImageStat.Stat(img_yuv).mean[0] luminance_std = ImageStat.Stat(img_yuv).stddev[0] img_hsv = img.convert('HSV') #min, max, avg, std of saturation saturation_min, saturation_max = ImageStat.Stat(img_hsv).extrema[0] saturation_avg = ImageStat.Stat(img_hsv).mean[0] saturation_std = ImageStat.Stat(img_hsv).stddev[0] pix = np.array(img) / 255 rg = (pix[:, :, 0] - pix[:, :, 1]).flatten() yb = ((pix[:, :, 0] + pix[:, :, 1]) / 2 - pix[:, :, 2]).flatten() s_rg = rg.std() s_yb = yb.std() u_rg = rg.mean() u_yb = yb.mean() # Colorfulness colorfulness = np.sqrt(s_rg**2 + s_yb**2) + 0.3 * np.sqrt(u_rg**2 + u_yb**2) # Lightness: # L = (Cmax + Cmin) / 2 lightness = (np.max(pix[:, :, 0:2], axis=2) + np.min(pix[:, :, 0:2], axis=2)) / 2 lightness_max = lightness.max() lightness_min = lightness.min() lightness_std = lightness.std() lightness_avg = lightness.mean() yield item_id, image_id, [ width, height, width * height, luminance_min, luminance_max, luminance_avg, luminance_std, saturation_min, saturation_max, saturation_avg, saturation_std, colorfulness, lightness_min, lightness_max, lightness_avg, lightness_std ]
def _get_brightness(self, image): grayscale = image.convert('L') stat = ImageStat.Stat(grayscale) return stat.mean[0]
def get_avg_brightness(): im = Image.open('/dev/shm/mjpeg/cam.jpg').convert('L') stat = ImageStat.Stat(im) total = stat.mean[0] return total
def brigthness values(folder, sample=True, xtension='*'): ''' ''' df = pd.DataFrame() files = [] print('Finding files...') for file in os.listdir(folder): if extension == '*': files.append(file) else: if file.endswith(extension): files.append(file) print('Done.') dates_list = [] avgpx_list = [] print('Reading images...') i = 1 tot = len(files) for img_path in files: print('\tProcessing {}, {}/{}'.format(img_path, i, tot)) # read imgae file with PIL img = Image.open(img_path) # fetch original date from img metadata date = img._getexif()[36867] # convert image to black and white bwimg = img.convert('L') # compute average brightness avgpx = ImageStat.Stat(bwimg).mean[0] dates_list.append(date) avgpx_list.append(avgpx) i = i + 1 print('Done.') print('Making df...') df['file'] = files df['date'] = dates_list df['brightness'] = avgpx_list df = df.sort_values(by='date') df = df.reset_index(drop=True) print('Done.') print('Getting deltas...') deltas_list = [] for i in range(1, len(df['brightness'])): delta = df['brightness'][i] - df['brightness'][i-1] deltas_list.append(delta) print('Done') deltas_list = [np.nan] + deltas_list df['delta'] = deltas_list return df
# Search the left template image matching with the right template image. for i in range(0, width-overlappingPixels, 1): # Get a template sample of the leftGTImage. # This template is sliding from the right to the left by a step of 1 pixel. leftTemplateImage = leftGTImage[:, width-overlappingPixels-1-i:width-1-i] # Perform the difference between the two images. # If the pixel is black, so the difference is perfect, and the pixel of the right template matches with the pixel to # the right image. newDiffImage = (leftTemplateImage - rightTemplateImage) # Compute the sum of all the pixel values of the new image. # More the sum is closed to 0, more the two images match. newDiffImage = Image.fromarray(newDiffImage) stat = ImageStat.Stat(newDiffImage) # Update the progressbar. pt3.update() # Keep in memory the minimum over the iteration. if sum(stat.sum) < diff: diff = sum(stat.sum) index = i # Finish the progressbar. pt3.finish() print("\nWe found the overlapping beginning.")
def calculate_brightness(image): grayscale = image.convert('L') stat = ImageStat.Stat(grayscale) return stat.mean[0]
def __init__(self, f_ann: str, img_dir: Path): self.img_dir = img_dir with open(f_ann, "r") as json_f: ann = json.load(json_f) self.num_cats = len(ann["categories"]) self.num_imgs = len(ann["images"]) self.num_bboxs = len(ann["annotations"]) # build cat id to name, assign FRCNN self.cat2name = {c["id"]: c["name"] for c in ann["categories"]} self.class_map = ClassMap(list(self.cat2name.values())) # need to translate coco subset category id to indexable label id # expected labels w 0 = background self.lbl2cat = { self.class_map.get_name(n): c for c, n in self.cat2name.items() } self.cat2lbl = {cat: lbl for lbl, cat in self.lbl2cat.items()} self.lbl2cat[0] = (0, "background") self.cat2lbl[0] = 0 # img_id to file map self.img2fname = {img["id"]: img["file_name"] for img in ann["images"]} self.imgs = [{ "id": img_id, "file_name": img_fname } for (img_id, img_fname) in self.img2fname.items()] # build up some maps for later analysis self.img2l2bs: Dict = {} self.img2lbs: Dict = defaultdict(empty_list) self.l2ibs: Dict = defaultdict(empty_list) # anno_id = 0 for a in ann["annotations"]: img_id = a["image_id"] cat_id = a["category_id"] lbl_id = self.cat2lbl[cat_id] l2bs_for_img = self.img2l2bs.get( img_id, {lbl: [] for lbl in range(1 + len(self.cat2name))}) (x, y, w, h) = a["bbox"] if w > 1 and h > 1: b = (x, y, w, h) ib = (img_id, *b) lb = (lbl_id, *b) l2bs_for_img[lbl_id].append(b) self.l2ibs[lbl_id].append(ib) self.img2lbs[img_id].append(lb) self.img2l2bs[img_id] = l2bs_for_img acc_ncats_per_img = 0.0 acc_nboxs_per_img = 0.0 for img_id, l2bs in self.img2l2bs.items(): acc_ncats_per_img += len(l2bs) for lbl_id, bs in l2bs.items(): acc_nboxs_per_img += len(bs) self.avg_ncats_per_img = acc_ncats_per_img / self.num_imgs self.avg_nboxs_per_img = acc_nboxs_per_img / self.num_imgs acc_nboxs_per_cat = 0.0 for lbl_id, ibs in self.l2ibs.items(): acc_nboxs_per_cat += len(ibs) self.avg_nboxs_per_cat = acc_nboxs_per_cat / self.num_cats # compute Images per channel means and std deviation using PIL.ImageStat.Stat() self.img2sz = {} n = 0 mean = np.zeros((3, )) stddev = np.zeros((3, )) avgw = 0 avgh = 0 for img in tqdm(self.imgs): img_id = img["id"] fname = f"{img_dir}/{img['file_name']}" n = n + 1 img = Image.open(fname) istat = ImageStat.Stat(img) width, height = img.size avgw = (width + (n - 1) * avgw) / n avgh = (height + (n - 1) * avgh) / n self.img2l2bs[img_id][0].append(( width / 3, height / 3, width / 3, height / 3, )) # hack to add a backgrnd box mean = (istat.mean + (n - 1) * mean) / n stddev = (istat.stddev + (n - 1) * stddev) / n self.img2sz[fname] = (width, height) self.chn_means = mean self.chn_stds = stddev self.avg_width = avgw self.avg_height = avgh
def brightness_pixel_rms_then_pb(im_file): im = Image.open(im_file) stat = ImageStat.Stat(im) r, g, b = stat.rms return sr(0.241 * (r**2) + 0.691 * (g**2) + 0.068 * (b**2))
def process(self): """Clip text regions / lines of the workspace at intersections with neighbours. Open and deserialise PAGE input files and their respective images, then iterate over the element hierarchy down to the requested ``level-of-operation``. Next, get each segment image according to the layout annotation (by cropping via coordinates into the higher-level image), as well as all its neighbours', binarize them (without deskewing), and make a connected component analysis. (Segments must not already have AlternativeImage annotated, otherwise they will be skipped.) Then, for each section of overlap with a neighbour, re-assign components which are only contained in the neighbour by clipping them to white (background), and export the (final) result as image file. Add the new image file to the workspace along with the output fileGrp, and using a file ID with suffix ``.IMG-CLIP`` along with further identification of the input element. Reference each new image in the AlternativeImage of the element. Produce a new output file by serialising the resulting hierarchy. """ # This makes best sense for overlapping segmentation, like current GT # or Tesseract layout analysis. Most notably, it can suppress graphics # and separators within or across a region or line. It _should_ ideally # be run after binarization (on page level for region-level clipping, # and on the region level for line-level clipping), because the # connected component analysis after implicit binarization could be # suboptimal, and the explicit binarization after clipping could be, # too. However, region-level clipping _must_ be run before region-level # deskewing, because that would make segments incomensurable with their # neighbours. LOG = getLogger('processor.OcropyClip') level = self.parameter['level-of-operation'] assert_file_grp_cardinality(self.input_file_grp, 1) assert_file_grp_cardinality(self.output_file_grp, 1) for (n, input_file) in enumerate(self.input_files): LOG.info("INPUT FILE %i / %s", n, input_file.pageId or input_file.ID) file_id = make_file_id(input_file, self.output_file_grp) pcgts = page_from_file(self.workspace.download_file(input_file)) self.add_metadata(pcgts) page_id = pcgts.pcGtsId or input_file.pageId or input_file.ID # (PageType has no id) page = pcgts.get_Page() page_image, page_coords, page_image_info = self.workspace.image_from_page( page, page_id, feature_selector='binarized') if self.parameter['dpi'] > 0: zoom = 300.0/self.parameter['dpi'] elif page_image_info.resolution != 1: dpi = page_image_info.resolution if page_image_info.resolutionUnit == 'cm': dpi *= 2.54 LOG.info('Page "%s" uses %f DPI', page_id, dpi) zoom = 300.0/dpi else: zoom = 1 regions = list(page.get_TextRegion()) num_texts = len(regions) regions += ( page.get_AdvertRegion() + page.get_ChartRegion() + page.get_ChemRegion() + page.get_GraphicRegion() + page.get_ImageRegion() + page.get_LineDrawingRegion() + page.get_MathsRegion() + page.get_MusicRegion() + page.get_NoiseRegion() + page.get_SeparatorRegion() + page.get_TableRegion() + page.get_UnknownRegion()) if not num_texts: LOG.warning('Page "%s" contains no text regions', page_id) background = ImageStat.Stat(page_image) # workaround for Pillow#4925 if len(background.bands) > 1: background = tuple(background.median) else: background = background.median[0] if level == 'region': background_image = Image.new(page_image.mode, page_image.size, background) page_array = pil2array(page_image) page_bin = np.array(page_array <= midrange(page_array), np.uint8) # in absolute coordinates merely for comparison/intersection shapes = [Polygon(polygon_from_points(region.get_Coords().points)) for region in regions] # in relative coordinates for mask/cropping polygons = [coordinates_of_segment(region, page_image, page_coords) for region in regions] for i, polygon in enumerate(polygons[num_texts:], num_texts): # for non-text regions, extend mask by 3 pixels in each direction # to ensure they do not leak components accidentally # (accounts for bad cropping of such regions in GT): polygon = Polygon(polygon).buffer(3).exterior.coords[:-1] # keep open polygons[i] = polygon masks = [pil2array(polygon_mask(page_image, polygon)).astype(np.uint8) for polygon in polygons] for i, region in enumerate(regions): if i >= num_texts: break # keep non-text regions unchanged if level == 'region': if region.get_AlternativeImage(): # FIXME: This should probably be an exception (bad workflow configuration). LOG.warning('Page "%s" region "%s" already contains image data: skipping', page_id, region.id) continue shape = prep(shapes[i]) neighbours = [(regionj, maskj) for shapej, regionj, maskj in zip(shapes[:i] + shapes[i+1:], regions[:i] + regions[i+1:], masks[:i] + masks[i+1:]) if shape.intersects(shapej)] if neighbours: self.process_segment(region, masks[i], polygons[i], neighbours, background_image, page_image, page_coords, page_bin, input_file.pageId, file_id + '_' + region.id) continue # level == 'line': lines = region.get_TextLine() if not lines: LOG.warning('Page "%s" region "%s" contains no text lines', page_id, region.id) continue region_image, region_coords = self.workspace.image_from_segment( region, page_image, page_coords, feature_selector='binarized') background_image = Image.new(region_image.mode, region_image.size, background) region_array = pil2array(region_image) region_bin = np.array(region_array <= midrange(region_array), np.uint8) # in absolute coordinates merely for comparison/intersection shapes = [Polygon(polygon_from_points(line.get_Coords().points)) for line in lines] # in relative coordinates for mask/cropping polygons = [coordinates_of_segment(line, region_image, region_coords) for line in lines] masks = [pil2array(polygon_mask(region_image, polygon)).astype(np.uint8) for polygon in polygons] for j, line in enumerate(lines): if line.get_AlternativeImage(): # FIXME: This should probably be an exception (bad workflow configuration). LOG.warning('Page "%s" region "%s" line "%s" already contains image data: skipping', page_id, region.id, line.id) continue shape = prep(shapes[j]) neighbours = [(linej, maskj) for shapej, linej, maskj in zip(shapes[:j] + shapes[j+1:], lines[:j] + lines[j+1:], masks[:j] + masks[j+1:]) if shape.intersects(shapej)] if neighbours: self.process_segment(line, masks[j], polygons[j], neighbours, background_image, region_image, region_coords, region_bin, input_file.pageId, file_id + '_' + region.id + '_' + line.id) # update METS (add the PAGE file): file_path = os.path.join(self.output_file_grp, file_id + '.xml') pcgts.set_pcGtsId(file_id) out = self.workspace.add_file( ID=file_id, file_grp=self.output_file_grp, pageId=input_file.pageId, local_filename=file_path, mimetype=MIMETYPE_PAGE, content=to_xml(pcgts)) LOG.info('created file ID: %s, file_grp: %s, path: %s', file_id, self.output_file_grp, out.local_filename)
from PIL import Image, ImageStat import picamera import requests import time while True: while True: print("first while") with picamera.PiCamera() as camera: camera.resolution = (1280, 720) camera.capture("/home/pi/test.jpg") print("Picture taken.") im = Image.open("test.jpg").convert("RGB") stat = ImageStat.Stat(im) if sum(stat.sum) / 3 != stat.sum[0]: #not black print("second while") camera.capture("/home/pi/light.jpg") print("d") camera.capture("/home/pi/test.jpg") print("dd") im = Image.open("test.jpg").convert("RGB") print("ddd") stat = ImageStat.Stat(im) print("dddd") else: #if sum(stat.sum)/3 == stat.sum[0]:#black print("black and send light pic") URL = "http://192.168.1.3:5000/" files = {'image': open('/home/pi/light.jpg')} r = requests.post(URL, files=files) print(r.text) break
def percentImageError(imageA, imageB): stat1 = ImageStat.Stat(imageA) stat2 = ImageStat.Stat(imageB) return math.fabs(stat1.stddev[0] - stat2.stddev[0])/stat1.stddev[0]
def getMean(self): if not self.mean: self.mean = ImageStat.Stat(self.im.convert('L')).mean[0] return self.mean
with open(input_filename, newline = '') as csv_file, \ open(output_filename, 'w') as output_file: reader = csv.reader(csv_file, skipinitialspace=True) next(reader) # Skip header # For each mammogram for row in reader: filename = row[3] basename = filename[:-4] # Load the mammogram and label mammogram = Image.open(filename) label = Image.open(basename + "_mask.png") # Enhance it (global background reduction + normalization) stat = ImageStat.Stat(mammogram, label) global_mean = stat.mean[0] mammogram = Image.eval( mammogram, lambda x: global_mean if x <= global_mean else x) mammogram = ImageOps.autocontrast(mammogram) # Downsample it new_width = round(mammogram.width * downsampling_factor) new_height = round(mammogram.height * downsampling_factor) mammogram = mammogram.resize((new_width, new_height), Image.LANCZOS) label = label.resize((new_width, new_height), Image.NEAREST) # Crop the image to delete unnnecesary background. Make sure every # dimension is divisible by 16 (our network subsampling factor) bbox = label.getbbox() # bounding-box 4-tuple: upper-left x, # upper-left y, lower-right x, lower-right y
def cutPageNumber(self, fixedThreshold): if ImageChops.invert(self.image).getbbox() is not None: widthImg, heightImg = self.image.size delta = 2 diff = delta if ImageStat.Stat(self.image).var[0] < 2 * fixedThreshold: return self.image while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] < fixedThreshold\ and diff < heightImg: diff += delta diff -= delta pageNumberCut1 = diff if diff < delta: diff = delta oldStat = ImageStat.Stat( self.image.crop( (0, heightImg - diff, widthImg, heightImg))).var[0] diff += delta while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] - oldStat > 0\ and diff < heightImg // 4: oldStat = ImageStat.Stat( self.image.crop( (0, heightImg - diff, widthImg, heightImg))).var[0] diff += delta diff -= delta pageNumberCut2 = diff diff += delta oldStat = ImageStat.Stat( self.image.crop((0, heightImg - diff, widthImg, heightImg - pageNumberCut2))).var[0] while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg - pageNumberCut2))).var[0]\ < fixedThreshold + oldStat and diff < heightImg // 4: diff += delta diff -= delta pageNumberCut3 = diff delta = 5 diff = delta while ImageStat.Stat(self.image.crop((0, heightImg - pageNumberCut2, diff, heightImg))).var[0]\ < fixedThreshold and diff < widthImg: diff += delta diff -= delta pageNumberX1 = diff diff = delta while ImageStat.Stat( self.image.crop( (widthImg - diff, heightImg - pageNumberCut2, widthImg, heightImg ))).var[0] < fixedThreshold and diff < widthImg: diff += delta diff -= delta pageNumberX2 = widthImg - diff if pageNumberCut3 - pageNumberCut1 > 2 * delta\ and float(pageNumberX2 - pageNumberX1) / float(pageNumberCut2 - pageNumberCut1) <= 9.0\ and ImageStat.Stat(self.image.crop((0, heightImg - pageNumberCut3, widthImg, heightImg))).var[0]\ / ImageStat.Stat(self.image).var[0] < 0.1\ and pageNumberCut3 < heightImg / 4 - delta: diff = pageNumberCut3 else: diff = pageNumberCut1 self.image = self.image.crop((0, 0, widthImg, heightImg - diff))
def __init__(self, path, image): self.path = path self.image = image self.median = ImageStat.Stat(image).median self.rect = pygame.Rect(0, 0, image.size[0], image.size[1])
def brightness(im_file): im = Image.open(im_file).convert("L") stat = ImageStat.Stat(im) return stat.mean[0], stat.rms[0]
def on_push_state(*args): img = Image.new('RGBA', (240, 240), color=(0, 0, 0, 25)) global status global service global ipaddress global tracktype global isScreenOn if 'status' in args[0]: status = args[0]['status'].encode('ascii', 'ignore') else: status = 'unknown' if 'service' in args[0]: service = args[0]['service'].encode('ascii', 'ignore') else: service = 'unknown' if 'uri' in args[0]: print('URI ' + args[0]['uri']) if 'trackType' in args[0]: tracktype = args[0]['trackType'] print('Tract Type ' + tracktype) else: tracktype = "unknown" volume = args[0]['volume'] print("Volume: {}".format(volume)) canseek = 0 if 'duration' in args[0]: duration = args[0]['duration'] # seconds if duration != 0: if 'seek' in args[0]: seek = args[0]['seek'] # time elapsed seconds if isinstance(seek, int): if seek != 0: canseek = 1 print("Can Seek: {}".format(canseek)) # Load albumcover or radio cover albumart = args[0]['albumart'].encode('ascii', 'ignore') getart = 0 if len(albumart) == 0: # to catch a empty field on start img = getBackgroundImage() print('Album Art Length Zero - using default Service: ' + service) elif 'http' not in albumart: if albumart == '/albumart': img = getBackgroundImage() print('Album Art /albumart - using default Service: ' + service) else: albumart = 'http://localhost:3000' + args[0]['albumart'] response = requests.get(albumart) img = Image.open(BytesIO(response.content)) img = img.resize((WIDTH, HEIGHT)) if img.mode != "RGBA": img = img.convert("RGBA") print('Album Art: ' + albumart + ' Service: ' + service) else: print('Album Art: ' + albumart + ' Service: ' + service) response = requests.get(albumart) img = Image.open(BytesIO(response.content)) img = img.resize((WIDTH, HEIGHT)) if img.mode != "RGBA": img = img.convert("RGBA") # Light / Dark Symbols an bars, depending on background im_stat = ImageStat.Stat(img) im_mean = im_stat.mean mn = mean(im_mean) txt_col = (255, 255, 255) bar_bgcol = (200, 200, 200) bar_col = (255, 255, 255) dark = False if mn > 175: txt_col = (55, 55, 55) dark = True bar_bgcol = (255, 255, 255) bar_col = (100, 100, 100) if mn < 80: txt_col = (200, 200, 200) # paste button symbol overlay in light/dark mode if service != "airplay_emulation": if status == 'play': if dark is False: img.paste(pause_icons, (0, 0), pause_icons) else: img.paste(pause_icons_dark, (0, 0), pause_icons_dark) else: if dark is False: img.paste(play_icons, (0, 0), play_icons) else: img.paste(play_icons_dark, (0, 0), play_icons_dark) # Set Icon on top right hand corner based on source shownames = 0 if tracktype == "airplay": img.paste(airplay_overlay, (0, 0), airplay_overlay) shownames = 1 elif service == "mpd": img.paste(mpd_overlay, (0, 0), mpd_overlay) shownames = 1 elif service == "webradio": img.paste(webradio_overlay, (0, 0), webradio_overlay) shownames = 0 elif service == "spop": img.paste(spotify_overlay, (0, 0), spotify_overlay) shownames = 1 elif service == "volspotconnect2": img.paste(spotify_overlay, (0, 0), spotify_overlay) shownames = 1 elif tracktype == "tidal": img.paste(tidal_overlay, (0, 0), tidal_overlay) shownames = 1 elif tracktype == "qobuz": img.paste(qobuz_overlay, (0, 0), qobuz_overlay) shownames = 1 elif tracktype == "bt": img.paste(bluetooth_overlay, (0, 0), bluetooth_overlay) shownames = 0 else: img.paste(bluetooth_overlay, (0, 0), bluetooth_overlay) shownames = 0 draw = ImageDraw.Draw(img, 'RGBA') top = 7 if 'artist' in args[0]: x1 = 20 w1, y1 = draw.textsize(args[0]['artist'], font_m) x1 = x1 - 20 if x1 < (WIDTH - w1 - 20): x1 = 0 if w1 <= WIDTH: x1 = (WIDTH - w1) // 2 if shownames == 1: draw.text((x1, top), args[0]['artist'], font=font_m, fill=txt_col) top = 35 if 'album' in args[0]: if args[0]['album'] is not None: x2 = 20 w2, y2 = draw.textsize(args[0]['album'], font_s) x2 = x2 - 20 if x2 < (WIDTH - w2 - 20): x2 = 0 if w2 <= WIDTH: x2 = (WIDTH - w2) // 2 if shownames == 1: draw.text((x2, top), args[0]['album'], font=font_s, fill=txt_col) if 'title' in args[0]: # Does the title fit on one line x3 = 20 w3, y3 = draw.textsize(args[0]['title'], font_l) x3 = x3 - 20 if x3 < (WIDTH - w3 - 20): x3 = 0 if w3 <= WIDTH: x3 = (WIDTH - w3) // 2 if shownames == 1: draw.text((x3, 105), args[0]['title'], font=font_l, fill=txt_col) # fill by mean # volume bar # Not present for airplay_emulation if service != "airplay_emulation": vol_x = int((float(args[0]['volume']) / 100) * (WIDTH - 33)) draw.rectangle((5, 184, WIDTH - 34, 184 + 8), bar_bgcol) # background draw.rectangle((5, 184, vol_x, 184 + 8), bar_col) volumeText = "Volume: {}".format(args[0]['volume']) x2 = 0 w2, y2 = draw.textsize(volumeText, font_s) if w2 <= WIDTH: x2 = (WIDTH - w2) // 2 draw.text((x2, 154), volumeText, font=font_s, fill=txt_col) # time bar if canseek == 1: el_time = int(float(args[0]['seek']) / 1000) du_time = int(float(args[0]['duration'])) dur_x = int((float(el_time) / float(du_time)) * (WIDTH - 10)) draw.rectangle((5, 222, WIDTH - 5, 222 + 12), bar_bgcol) # background draw.rectangle((5, 222, dur_x, 222 + 12), bar_col) # Draw the image on the display hardware disp.display(img)
from PIL import Image, ImageStat import glob import matplotlib import matplotlib.pyplot as plt DROP = '/groups/dickson/home/bathd/Dropbox/140827_no_arena_zoom/' images = sorted(glob.glob(DROP + '*.png')) medians = [] totals = [] for x in images: im = Image.open(x) med = ImageStat.Stat(im).median total = ImageStat.Stat(im).sum medians.append(med) totals.append(total) fig = plt.figure() ax = fig.add_subplot(2,1,1) plt.plot(medians, color='g', linewidth=2) plt.xlabel('Position', fontsize=12) plt.ylabel('Median pixel intensity (AU)', fontsize=12) ax2 = fig.add_subplot(2,1,2) plt.plot(totals, color='g', linewidth=2) plt.xlabel('Position', fontsize=12) plt.ylabel('Sum pixel intensity (AU)', fontsize=12)
def brightness(im_file): im = Image.fromarray(im_file).convert('L') stat = ImageStat.Stat(im) return stat.mean[0]
def average_luma(imgname): img = Image.open(imgname) if img.mode == 'RGB': img = img.convert('L') return (imgname, ImageStat.Stat(img, mask=IMASK).mean[0])
def avg_image(im): """ Return average r,g,b for image""" return [int(x) for x in ImageStat.Stat(im).mean]
def mosaic(image, size=(80, 80), block=0, axis=None, prob=0.3, p=1): """mosaic noise apply to image. Args: image: a PIL instance. size: if int or float, xsize=ysize, how many mosaic blocks the image is divided into. if 2-tuple, (xsize, ysize), if 4-tuple, xsize in (size[0], size[1]) and ysize in (size[2], size[3]). block: mosaic area block axis: list or tuple, one or more mosaic center axis point. prob: probability of numbers of mosaci. p: probability that the image does this. Default value is 1. Return: a PIL instance. """ if isinstance(size, (int, float)): size = (size, size) elif isinstance(size, (list, tuple)): if len(size) == 4: size = (np.random.uniform(size[0], size[1]), np.random.uniform(size[2], size[3])) elif len(size) != 2: raise ValueError('`size` value format error.') else: raise ValueError('`size` value format error.') size = (max(2, int(size[0])), max(2, int(size[1]))) if axis is not None: if isinstance(axis[0], (list, tuple)): block = max(block, len(axis)) axis_num = len(axis) else: block = max(block, 1) axis_num = 1 axis = [axis] w = image.size[0] // size[0] h = image.size[1] // size[1] image2 = image.copy() if block == 0: axis_list = [[i * w, j * h, i * w + w, j * h + h] for i in range(size[0]) for j in range(size[1])] s = np.random.choice(range(size[0] * size[1]), max(int(size[0] * size[1] * prob), 2), replace=False) for i in s: image2.paste( Image.new( image.mode, (w, h), tuple([ int(j) for j in ImageStat.Stat(image.crop(axis_list[i])).mean ])), axis_list[i]) else: num = max(int(size[0] * size[1] * prob / block), 2) edge = np.sqrt(num) for b in range(int(block)): if axis is not None: if b <= axis_num - 1: axis_list = [axis[b][0] / w, axis[b][1] / h] else: axis_list = [ np.random.uniform(edge / 2 / size[0], 1 - edge / 2 / size[0]) * size[0], np.random.uniform(edge / 2 / size[1], 1 - edge / 2 / size[0]) * size[1] ] else: axis_list = [ np.random.uniform(edge / 2 / size[0], 1 - edge / 2 / size[0]) * size[0], np.random.uniform(edge / 2 / size[1], 1 - edge / 2 / size[0]) * size[1] ] axis_prob = [] axis_must = [] for i in range(int(axis_list[0] - edge / 2), int(axis_list[0] + edge / 2) + 1): for j in range(int(axis_list[1] - edge / 2), int(axis_list[1] + edge / 2) + 1): if i < int(axis_list[0] - edge / 3) or i > int( axis_list[0] + edge / 3) or j < int( axis_list[1] - edge / 3) or j > int(axis_list[1] + edge / 3): axis_prob.append([i * w, j * h, i * w + w, j * h + h]) else: axis_must.append([i * w, j * h, i * w + w, j * h + h]) s = np.random.choice(range(len(axis_prob)), int(len(axis_prob) * 0.8), replace=False) for i in s: image2.paste( Image.new( image.mode, (w, h), tuple([ int(j) for j in ImageStat.Stat( image.crop(axis_prob[i])).mean ])), axis_prob[i]) for i in axis_must: image2.paste( Image.new( image.mode, (w, h), tuple([ int(j) for j in ImageStat.Stat(image.crop(i)).mean ])), i) return image2
def brightness(self, img): stat = ImageStat.Stat(img) r, g, b = stat.rms return math.sqrt(0.241 * (r**2) + 0.691 * (g**2) + 0.068 * (b**2))
def brightness2(self, im_file): im = Image.open(im_file) stat = ImageStat.Stat(im) r, g, b = stat.mean[:3] return math.sqrt(0.241 * (r**2) + 0.691 * (g**2) + 0.068 * (b**2))
def brightness_alt(self, img): im = img.convert('L') stat = ImageStat.Stat(im) return stat.mean[0]
import subprocess import os hostname = 'uc2pi.attlocal.net' preview = False crop_center = False sleep_time = .5 last_vals = deque() # a queue while (True): response = requests.get('http://{}/html/cam_pic.php'.format(hostname)) buf = io.BytesIO(response.content) img = Image.open(buf) width = img.size[0] height = img.size[1] crop_x = (width - height) / 2 if crop_center: img = img.crop((crop_x, 0, crop_x + height, height)) img.save('/tmp/focus.png', "png") if preview: viewer = subprocess.Popen(['feh', "/tmp/focus.png"]) var = ImageStat.Stat(img).var if len(last_vals) == 3: last_vals.popleft() last_vals.append(var) print("variance:\t{:8>f}\t{:8>f}\t{:8>f}".format( *np.mean(last_vals, axis=0))) sleep(sleep_time) if preview: viewer.terminate() viewer.kill()
f = open(finbasename + '.mtl', 'r') for line in f.readlines(): items = line.split() if not items: continue if items[0] == 'newmtl': mtlname = items[1] dico_mtl[mtlname] = [[0, 0, 0, 1], ''] elif items[0] == 'Kd': dico_mtl[mtlname][0][0:3] = [float(x) for x in items[1:4]] elif items[0] == 'd': dico_mtl[mtlname][0][3] *= float(items[1]) elif items[0] == 'map_Kd': texture_name = ' '.join(items[1:]) if os.path.isfile(texture_name): im = Image.open(texture_name) mean = ImageStat.Stat(im).mean #print("mean : ",mean) stddev = [ round(x * 10) / 10 for x in ImageStat.Stat(im).stddev ] if numpy.max(numpy.array(stddev)) < min_stddev_thresh: if debug_level >= 2: print(" Texture ", texture_name.split('/')[-1], " will be transformed into plain color") print( " due to its low standard deviation for each of its bands : ", stddev) print() dico_mtl[mtlname][0][0:3] = [x / 255 for x in mean[0:3]] try: