def screenshot(self,i): capture = cv2.VideoCapture(0) ret, frame = capture.read() cv2.imshow('capture',frame) base64= self.base64n(frame) new(i,base64) capture.release() #释放摄像头 cv2.destroyAllWindows()#删除建立的全部窗口 return 1
def inimagehandler(self, code, message, params): im = new('RGBA', (int(params['width']), int(params['height']))) im.putalpha(new('1', (int(params['width']), int(params['height'])))) draw = Draw(im) for count, line in enumerate(message.strip().split('\n')): draw.text((12,15*(count+1)), line, fill='#000000') fh = StringIO() im.save(fh, PIL_TYPE_MAPPING[params['format']]) fh.seek(0) return Response(params['format'], fh.read())
def inimagehandler(self, code, message, params): im = new("RGBA", (int(params["width"]), int(params["height"]))) im.putalpha(new("1", (int(params["width"]), int(params["height"])))) draw = Draw(im) for count, line in enumerate(message.strip().split("\n")): draw.text((12, 15 * (count + 1)), line, fill="#000000") fh = StringIO() im.save(fh, PIL_TYPE_MAPPING[params["format"]]) fh.seek(0) return Response(params["format"], fh.read())
def inimagehandler(self, code, message, params): im = new('RGBA', (int(params['width']), int(params['height']))) im.putalpha(new('1', (int(params['width']), int(params['height'])))) draw = Draw(im) for count, line in enumerate(message.strip().split('\n')): draw.text((12, 15 * (count + 1)), line, fill='#000000') fh = StringIO() im.save(fh, PIL_TYPE_MAPPING[params['format']]) fh.seek(0) return Response(params['format'], fh.read())
def blankhandler(self, code, message, params): bgcolor = params.get("bgcolor", "#FFFFFF") bgcolor = bgcolor.replace("0x", "#") transparent = params.get("transparent", "FALSE") if transparent == "TRUE": im = new("RGBA", (int(params["width"]), int(params["height"]))) im.putalpha(new("1", (int(params["width"]), int(params["height"])))) else: im = new("RGBA", (int(params["width"]), int(params["height"])), bgcolor) fh = StringIO() im.save(fh, PIL_TYPE_MAPPING[params["format"]]) fh.seek(0) return Response(params["format"], fh.read())
def blankhandler(self, code, message, params): bgcolor = params.get('bgcolor', '#FFFFFF') bgcolor = bgcolor.replace('0x', '#') transparent = params.get('transparent', 'FALSE') if transparent == 'TRUE': im = new('RGBA', (int(params['width']), int(params['height']))) im.putalpha(new('1', (int(params['width']), int(params['height'])))) else: im = new('RGBA', (int(params['width']), int(params['height'])), bgcolor) fh = StringIO() im.save(fh, PIL_TYPE_MAPPING[params['format']]) fh.seek(0) return Response(params['format'], fh.read())
def blankhandler(self, code, message, params): bgcolor = params.get('bgcolor', '#FFFFFF') bgcolor = bgcolor.replace('0x', '#') transparent = params.get('transparent', 'FALSE') if transparent in ('TRUE','true','True'): im = new('RGBA', (int(params['width']), int(params['height']))) im.putalpha(new('1', (int(params['width']), int(params['height'])))) else: im = new('RGBA', (int(params['width']), int(params['height'])), bgcolor) fh = StringIO() format = PIL_TYPE_MAPPING[params['format']].replace('256','') im.save(fh, format) fh.seek(0) return Response(params['format'].replace('8',''), fh.read(), status_code=404)
def get_image(cells, screen_size): img = new('RGB', (size, size), "white") pixels = img.load() for x, y in list(cells): pixels[x, y] = (194, 232, 247) return PhotoImage(img.resize((screen_size, screen_size)))
def GeneratePixelCoordinates(data): # A lot happens here. We first take data and turn it into byte values # array("B", data) is exactly like map(ord, data), but faster # grouper(2, ..., VALUE) takes [1,2,3,4,5] and returns ((1,2),(3,4),(5,VALUE)) # Tally counts the number of occurences of (1,2) and returns a dictionary # Then we turn the dictionary into a list of [(key,value), ...] # Then we sort by value in decending order (the lambda) # At the end of this, we end up with the locations of our pixels # and their colour values tallied = tally(grouper(2, array("B", data), 0)) lst = sorted(tallied.iteritems(), key=lambda x: -x[1]) # Since we ordered the list, the highest is the first element, and the # lowest is the last. Take the logs. highest = log(lst[0][1]) lowest = log(lst[-1][1]) if highest == lowest: return None, None # Take the logs, scale so that minimum is at 0, and highest is at 255. def compute(x): return (x[0], 255*(log(x[1]) - lowest) / (highest - lowest)) lst = map(compute, lst) # Here, we create a PIL image, and populate the relevent pixels. i = new("P", (256, 256)) i.putpalette(MakePalette()) for position, value in lst: i.putpixel(position, value) return i, lst
def test_insert_image_blob(self): img = new("RGB", (256, 256), "red") data = img_to_buf(img, 'jpeg').read() tempDB = self.__make_tempDB() tempDB.insert_image_blob(0, 0, 0, Binary(data)) result = tempDB.cursor.execute("select count(*) from tiles;") assert result.fetchone()[0] == 1
def test_img_to_buf_png(self): img = new("RGB", (256, 256), "red") img.save("test1.png", 'PNG') data = img_to_buf(img, 'png').read() # ImageHeaDeR, ImageDATa, and ImageEND are # all necessary chunks in a .PNG bitstream assert 'IHDR' in data and 'IDAT' in data and 'IEND' in data
def test_img_to_buf_source(self): img = new("RGB", (256, 256), "red") img.save("test2.jpg") img.format = "JPEG" data = img_to_buf(img, 'source').read() # a 'JFIF' chunk in the bitstream indicates a .jpg image assert 'JFIF' in data
def blankhandler(self, code, message, params): bgcolor = params.get('bgcolor', '#FFFFFF') bgcolor = bgcolor.replace('0x', '#') transparent = params.get('transparent', 'FALSE') if transparent in ('TRUE', 'true', 'True'): im = new('RGBA', (int(params['width']), int(params['height']))) im.putalpha(new('1', (int(params['width']), int(params['height'])))) else: im = new('RGBA', (int(params['width']), int(params['height'])), bgcolor) fh = StringIO() format = PIL_TYPE_MAPPING[params['format']].replace('256', '') im.save(fh, format) fh.seek(0) return Response(params['format'].replace('8', ''), fh.read(), status_code=404)
def MakePlainPlot(data): """Given a 1D length of data, turn it into a 2D plot the 'straightforward' way, by mapping bytes onto RGB components""" sqrtsize = int(len(data)**0.5) i = new("L", (sqrtsize, sqrtsize)) # Ensure data is a length % 3 = 0. (i.e. exactly fills the number of pixels) data = data[:-(len(data)%3)] i.fromstring(data) i.show()
def concat_horizontally(images_to_concat): w = images_to_concat[0].width * len(images_to_concat) h = images_to_concat[0].height img = new('RGB', (w, h)) for index, item in enumerate(images_to_concat): img.paste(item, (item.width * index, 0)) return img
def concat_vertically(images_to_concat): h = images_to_concat[0].height * len(images_to_concat) w = images_to_concat[0].width img = new('RGB', (w, h)) for index, item in enumerate(images_to_concat): img.paste(item, (0, item.height * index)) return img
def __getitem__(self, index): new_img = open(self.x_img_path[index]) if not self.is_grey_scale: rgb_img = new("RGB", new_img.size) rgb_img.paste(new_img) out_img = self.transform(new_img) return out_img, self.y_label[index] # data, target
def load_image(self, url: str) -> 'Image': response = self._session.get(url, timeout=2) if response.status_code != codes.ok: raise RampartError( f'Loader got non-ok status {response.status_code}') source = open(BytesIO(response.content)) if source.mode == 'RGBA': canvas = new('RGBA', source.size, 'white') canvas.paste(source, (0, 0), source) source = canvas.convert('RGB') return Image(url, source, Interior.unknown)
def gen_img(font_name, font_size, text, img_size): font = truetype(font_name + ".ttf", font_size) print(font.getsize("By")) width, height = img_size img = new("1", (width, height), 255) drawing = Draw(img) drawing.text((10, 10), text, fill=0, font=font) img = img.convert("L") img = np.asarray(img, dtype=np.uint8) return img
def process_image(self): file_path=self.get_path('*.*') print 'You selected', file_path img=open(file_path) gray_img=grayscale(img) gray_pixels=gray_img.getdata() new_img_pixels = self.make_cartoon_pic(gray_pixels, self.color_palette) img_new = new("RGB", img.size) img_new.putdata(new_img_pixels) img_new = self.make_dots(img_new, self.color_palette[2]) img_new=self.make_lines(img_new, self.color_palette[0]) import os img_new.save(os.path.dirname(file_path) + "/" + "Nicole_cartoon.jpg") #saves image--change the last string to whatever you want your image saved as
def test_combine_worker_dbs(): session_folder = make_session_folder() # make a random number of tempdbs with dummy data img = new("RGB", (256, 256), "red") data = img_to_buf(img, 'jpeg').read() z = randint(2, 5) for x in xrange(z): TempDB(session_folder).insert_image_blob(x, 0, 0, Binary(data)) # confirm that combine_worker_dbs assimilates all tempdb's into gpkg chdir(session_folder) # necessary to put gpkg in session_folder gpkg = Geopackage("test.gpkg", 4326) combine_worker_dbs(gpkg) result = gpkg.execute("select count(*) from tiles;") assert (result.fetchone())[0] == z
def process_image(self): """ changes an image to greyscale and calls functions to return an image with the new palette colors. Saves the new image and adds patterns to make it into a cartoon. """ # debugging print statement: # print("Processing image...) gray_image = grayscale(self.image) # change image to greyscale gray_pixels = gray_image.getdata( ) # get a list with the new greyscale colors for every pixel gray_image.save( "./img/grey_image_debug01.bmp") # save new greyscale image # CHECKING PROGRESS # for i in range(10): # print(gray_pixels[i]), # image = self.make_pattern(self.image, "FFFF00") # image.save("./img/pattern_test_debug02.bmp") # image = self.make_lines(self.image, "99FFFF") # image.save("./img/line_test_debug02.bmp") new_img_pixels = self.make_cartoon_pic( gray_pixels, self.color_palette) # get a new list for pixel's colors # debugging print statement: # print("img total pixels:", self.w * self.h) # print("new_img total pixels:", len(new_img_pixels)) assert (self.w * self.h == len(new_img_pixels)) new_pixels = self.make_cartoon_pic( gray_pixels, self.color_palette) # list pixels' new color palette new_image = new("RGB", self.image.size) # create an empty image new_image.putdata( new_pixels) # put new list of colors onto the new image new_image = self.make_pattern( new_image, self.color_palette[4], self.color_palette[3]) # add patterns to new image new_image = self.make_lines( new_image, self.color_palette[2], self.color_palette[0]) # add lines to new image new_image = self.diagonal_lines( new_image, self.color_palette[0], self.color_palette[2]) # add diagonal lines new_image.save("./img/new_image.bmp") # save new image
def concat_pictures(images: Subset) -> Tuple[Image, int]: assert len(images) == bag_size width = images[0][0].width height = images[0][0].height bag = new('L', (2 * width, 2 * height)) bag.paste(images[0][0], (0, 0)) bag.paste(images[1][0], (width, 0)) bag.paste(images[2][0], (0, height)) bag.paste(images[3][0], (width, height)) # is target_label in the created bag _, labels = zip(*images) label = int(target_label in labels) return bag, label
def plot(W): """ Plot basis vectors. :param W: Basis matrix of the fitted factorization model. :type W: `numpy.matrix` """ set_cmap('gray') blank = new("L", (225 + 6, 280 + 6)) for i in xrange(5): for j in xrange(5): basis = np.array(W[:, 5 * i + j])[:, 0].reshape((56, 46)) basis = basis / np.max(basis) * 255 basis = 255 - basis ima = fromarray(basis) expand(ima, border = 1, fill = 'black') blank.paste(ima.copy(), (j * 46 + j, i * 56 + i)) imshow(blank) savefig("orl_faces.png")
def process_image(self): """ """ img = open("./clown.bmp") # ! # print img.format, img.size, img.mode # view image attributes gray_img = grayscale(img) gray_pixels = list(gray_img.getdata()) gray_img.save("./" + "grey_img01.bmp") new_img_pixels = self.make_cartoon_pic(gray_pixels, self.color_palette) new_img = new("RGB", img.size) new_img.putdata(new_img_pixels) new_img = self.make_pattern(new_img, self.color_palette[2], (0, 255, 0)) new_img = self.make_lines(new_img, self.color_palette[4], (0, 255, 255)) new_img = self.make_rect(new_img, self.color_palette[1], (255, 255, 255)) new_img.save("./" + "final_img.bmp")
def plot(W): """ Plot basis vectors. :param W: Basis matrix of the fitted factorization model. :type W: `numpy.matrix` """ set_cmap('gray') blank = new("L", (225 + 6, 280 + 6)) for i in range(5): for j in range(5): basis = np.array(W[:, 5 * i + j])[:, 0].reshape((56, 46)) basis = basis / np.max(basis) * 255 basis = 255 - basis ima = fromarray(basis) expand(ima, border=1, fill='black') blank.paste(ima.copy(), (j * 46 + j, i * 56 + i)) imshow(blank) savefig("orl_faces.png")
def plot(W): """ Plot basis vectors. :param W: Basis matrix of the fitted factorization model. :type W: `numpy.matrix` """ set_cmap('gray') blank = new("L", (133 + 6, 133 + 6)) for i in range(7): for j in range(7): basis = np.array(W[:, 7 * i + j])[:, 0].reshape((19, 19)) basis = basis / np.max(basis) * 255 basis = 255 - basis ima = fromarray(basis) ima = ima.rotate(180) expand(ima, border=1, fill='black') blank.paste(ima.copy(), (j * 19 + j, i * 19 + i)) imshow(blank) savefig("cbcl_faces.png")
def plot(W): """ Plot basis vectors. :param W: Basis matrix of the fitted factorization model. :type W: `numpy.matrix` """ set_cmap('gray') blank = new("L", (133 + 6, 133 + 6)) for i in xrange(7): for j in xrange(7): basis = np.array(W[:, 7 * i + j])[:, 0].reshape((19, 19)) basis = basis / np.max(basis) * 255 basis = 255 - basis ima = fromarray(basis) ima = ima.rotate(180) expand(ima, border=1, fill='black') blank.paste(ima.copy(), (j * 19 + j, i * 19 + i)) imshow(blank) savefig("cbcl_faces.png")
def load_chars(font_name, size, chars): """Load characters from given font of given size. :param font_name: given font name :param size: given size :param chars: given set of characters :return: dict of tuples - character: (image, max_match_val) """ font = truetype(font_name + ".ttf", size) symbols = {} for char in chars: width, height = font.getsize(char) img = new("1", (width, height), 0) drawing = Draw(img) drawing.text((0, 0), char, fill=255, font=font) img = img.convert("L") img = np.asarray(img, dtype=np.uint8) if char != ' ': img = crop_text(img) symbols[char] = (img, match(img, img)) return symbols
def write_image(self, splat_scale=1.0): """Write the image to disk.""" # convert image to RGB and compute final pixel values n_pixels = self.x_pixel_count * self.y_pixel_count image = new("RGB", (self.x_pixel_count, self.y_pixel_count)) offset = 0 for j in xrange(self.y_pixel_count): for i in xrange(self.x_pixel_count): # convert pixel XYZ color to RGB x = self.pixels[j * self.x_pixel_count * 8 + i * 8] y = self.pixels[j * self.x_pixel_count * 8 + i * 8 + 1] z = self.pixels[j * self.x_pixel_count * 8 + i * 8 + 2] r, g, b = xyz_to_rgb(x, y, z) # normalize pixel with weight sum weight_sum = self.pixels[j * self.x_pixel_count * 8 + i * 8 + 3] if weight_sum != 0.0: inv_weight = 1.0 / weight_sum r = max(0.0, r * inv_weight) g = max(0.0, g * inv_weight) b = max(0.0, b * inv_weight) # add splat value at pixel x = self.pixels[j * self.x_pixel_count * 8 + i * 8 + 4] y = self.pixels[j * self.x_pixel_count * 8 + i * 8 + 5] z = self.pixels[j * self.x_pixel_count * 8 + i * 8 + 6] splat_r, splat_g, splat_b = xyz_to_rgb(x, y, z) r += splat_scale * splat_r g += splat_scale * splat_g b += splat_scale * splat_b r = int(255.0 * r) g = int(255.0 * g) b = int(255.0 * b) image.im.putpixel((i, j), (r, g, b)) image.save(self.filename)
def write_image(self, splat_scale=1.0): """Write the image to disk.""" # convert image to RGB and compute final pixel values n_pixels = self.x_pixel_count * self.y_pixel_count image = new("RGB", (self.x_pixel_count, self.y_pixel_count)) offset = 0 for j in xrange(self.y_pixel_count): for i in xrange(self.x_pixel_count): # convert pixel XYZ color to RGB x = self.pixels[j*self.x_pixel_count*8+i*8] y = self.pixels[j*self.x_pixel_count*8+i*8+1] z = self.pixels[j*self.x_pixel_count*8+i*8+2] r, g, b = xyz_to_rgb(x, y, z) # normalize pixel with weight sum weight_sum = self.pixels[j*self.x_pixel_count*8+i*8+3] if weight_sum != 0.0: inv_weight = 1.0 / weight_sum r = max(0.0, r * inv_weight) g = max(0.0, g * inv_weight) b = max(0.0, b * inv_weight) # add splat value at pixel x = self.pixels[j*self.x_pixel_count*8+i*8+4] y = self.pixels[j*self.x_pixel_count*8+i*8+5] z = self.pixels[j*self.x_pixel_count*8+i*8+6] splat_r, splat_g, splat_b = xyz_to_rgb(x, y, z) r += splat_scale * splat_r g += splat_scale * splat_g b += splat_scale * splat_b r = int(255.0 * r) g = int(255.0 * g) b = int(255.0 * b) image.im.putpixel((i, j), (r, g, b)) image.save(self.filename)
def render(self, path, width=None, height=None): """ Render chart @param str path: @param int width: @param int height: """ if not width: width = 320 if not height: height = 240 # mode = "RGB" size = (width, height) color = (255, 255, 255) im = new(mode, size, color=color) draw = Draw(im) axis_x = AxisX(width, height) self._render_axes(draw, width, height, axis_x=axis_x) self._render_values(draw, width, height, axis_x=axis_x) # im.save(path, format="PNG")
def test_img_to_buf_jpg(self): img = new("RGB", (256, 256), "red") data = img_to_buf(img, 'jpeg').read() # a 'JFIF' chunk in the bitstream indicates a .jpg image assert 'JFIF' in data
def add_border(img, width): nw = new('RGB', (img.width + 2 * width, img.height), (255, 255, 255)) nw.paste(img, (int(width / 2), 0)) return nw
def test_not_transparent(self): img = new("RGB", (256, 256), "red") assert img_has_transparency(img) == 0
def test_partially_transparent(self): img = new("RGBA", (256, 256)) draw = ImageDraw.Draw(img) draw.ellipse((96, 96, 160, 160), fill=(255, 0, 0)) assert img_has_transparency(img) > 0
def test_paletted_image_not_transparent(self): img = new('P', (256, 256)) assert img_has_transparency(img) == 0
def test_paletted_image_transparent(self): img = new("P", (256, 256), 0) img.save("test1.png", "PNG", transparency="\x00") img = iopen("test1.png", "r") assert img_has_transparency(img)
def test_fully_transparent(self): img = new('RGBA', (256, 256)) assert img_has_transparency(img) == -1