def fill(self,seedPoint,fillValue=1 ): "fills an area starting with seed" i = self.index(seedPoint); v = self.p[:]; x = Image.fromarray(v.T); ImageDraw.Draw(x); ImageDraw.floodfill(x,(i[0],i[1]),fillValue); v[:] = np.array(x).T;
def createMask(imageIn, threshold=10, fillHoles=True, backgroundColor=255, blurRadius=0.0, maskScale=1.0): """ Given an image, create a mask by locating the pixels that are not the backgroundColor (within a threshold). @param threshold How far away from the backgroundColor a pixel must be to be included in the mask @param fillHoles If true, the inside of the mask will be filled in. This is useful if the inside of objects might contain the background color @param backgroundColor the background color. @param blurRadius If set to some fraction > 0.0, then the edges of the mask will be blurred using a blur radius which is this fraction of the image size. @param maskScale If set to < 1.0, then the effective size of the object (the area where the mask includes the object) will be scaled down by this amount. This can be useful when the outside of the object contains some noise that you want to trim out and not include in the mask. @retval the mask as a PIL 'L' image, where 255 is areas that include the object, and 0 are areas that are background. If blurRadius is > 0, then it will also contain values between 0 and 255 which act as compositing values. """ image = imageIn.convert('L') bwImage = image.point(lambda x: (abs(x - backgroundColor) > threshold) * 255) if not fillHoles: mask = bwImage else: bwImage = ImageOps.expand(bwImage, 1, fill=0) maskColor = 128 ImageDraw.floodfill(bwImage, (0, 0), maskColor) mask = bwImage.point(lambda x: (x != maskColor) * 255) mask = ImageOps.crop(mask, 1) # Are we reducing the object size? if maskScale < 1.0: newSize = [int(x * maskScale) for x in mask.size] reducedMask = mask.resize(newSize, Image.ANTIALIAS) sizeDiff = numpy.array(mask.size) - numpy.array(newSize) pos = [int(x / 2) for x in sizeDiff] mask = ImageChops.constant(mask, 0) mask.paste(reducedMask, tuple(pos)) # Blur the mask if blurRadius > 0.0: radius = int(round(blurRadius * (mask.size[0] + mask.size[1]) / 2)) if radius > 1: mask = blur(mask, radius=radius, edgeColor=0) else: import pdb; pdb.set_trace() return mask
def fillImageFaster(self, begin, paint, current, image): buffer = QBuffer() buffer.open(QBuffer.ReadWrite) image.save(buffer, "PNG") pil_im = Image.open(io.BytesIO(buffer.data())) ImageDraw.floodfill(pil_im, begin, (paint.red(), paint.green(), paint.blue())) self.image().image = QtGui.QImage(pil_im.convert("RGB").tobytes("raw", "RGB"), pil_im.size[0], pil_im.size[1], QtGui.QImage.Format_RGB888) self.update()
def test_floodfill(): # Arrange im = Image.new("RGB", (w, h)) draw = ImageDraw.Draw(im) draw.rectangle(bbox2, outline="yellow", fill="green") centre_point = (int(w/2), int(h/2)) # Act ImageDraw.floodfill(im, centre_point, ImageColor.getrgb("red")) del draw # Assert assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill.png"))
def test_floodfill(self): # Arrange im = Image.new("RGB", (W, H)) draw = ImageDraw.Draw(im) draw.rectangle(BBOX2, outline="yellow", fill="green") centre_point = (int(W / 2), int(H / 2)) red = ImageColor.getrgb("red") im_floodfill = Image.open("Tests/images/imagedraw_floodfill.png") # Act ImageDraw.floodfill(im, centre_point, red) # Assert self.assert_image_equal(im, im_floodfill) # Test that using the same colour does not change the image ImageDraw.floodfill(im, centre_point, red) self.assert_image_equal(im, im_floodfill) # Test that filling outside the image does not change the image ImageDraw.floodfill(im, (W, H), red) self.assert_image_equal(im, im_floodfill) # Test filling at the edge of an image im = Image.new("RGB", (1, 1)) ImageDraw.floodfill(im, (0, 0), red) self.assert_image_equal(im, Image.new("RGB", (1, 1), red))
def test_floodfill(self): # Arrange im = Image.new("RGB", (W, H)) draw = ImageDraw.Draw(im) draw.rectangle(BBOX2, outline="yellow", fill="green") centre_point = (int(W / 2), int(H / 2)) # Act ImageDraw.floodfill(im, centre_point, ImageColor.getrgb("red")) del draw # Assert self.assert_image_equal( im, Image.open("Tests/images/imagedraw_floodfill.png"))
def __init__(self, simplemap): self.image = Image.new("RGB", simplemap.image.size) self.simple = simplemap ImageDraw.floodfill(self.image, (0, 0), (255, 255, 255)) self.territories = set() draw = ImageDraw.Draw(self.image) self.territory_colours = territory_colours = simplemap.get_territories() self.inv_territory_colours = inv_territory_colours = dict([(v, k) for (k, v) in territory_colours.items()]) for fillpass in range(3): for y in xrange(self.image.size[1]): for x in xrange(self.image.size[0]): colour = simplemap.image.getpixel((x, y)) if fillpass == 1 and colour in territory_colours.values(): tid = inv_territory_colours[colour] * 100 n_x, n_y = x, y neighbours = [(x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)] neighbours = [(x if x > 0 else self.image.size[0] - 1, y) for (x, y) in neighbours] neighbours = [(x if x < self.image.size[0] else 0, y) for (x, y) in neighbours] neighbours = [(x, y if y > 0 else self.image.size[1] - 1) for (x, y) in neighbours] neighbours = [(x, y if y < self.image.size[1] else 0) for (x, y) in neighbours] neighbours = set(self.image.getpixel(neighbour) for neighbour in neighbours) neighbours = set( colour for colour in neighbours if colour[2] < 255 and colour != (0, 0, 0) and colour != (255, 0, 0) ) if neighbours: colour = max(neighbours) tid = colour_to_territory_id(colour) else: tid = inv_territory_colours[colour] * 100 # generate a new tid tid += 1 while tid in self.territories: tid += 1 self.territories.add(tid) colour = territory_id_to_colour(tid) x, y = n_x, n_y ImageDraw.floodfill(self.image, (x, y), colour) elif colour == (255, 255, 255): if x < self.image.size[0] - 1: next_pixel = simplemap.image.getpixel((x + 1, y)) if fillpass == 2 and (next_pixel in territory_colours.values()): # We're not in the sea colour = self.image.getpixel((x + 1, y))[:2] + (255,) draw.point((x, y), tuple(colour)) continue draw.point((x, y), colour) elif colour in set([(0, 0, 0), (255, 0, 0)]): draw.point((x, y), colour)
def test_floodfill(self): red = ImageColor.getrgb("red") for mode, value in [ ("L", 1), ("RGBA", (255, 0, 0, 0)), ("RGB", red) ]: # Arrange im = Image.new(mode, (W, H)) draw = ImageDraw.Draw(im) draw.rectangle(BBOX2, outline="yellow", fill="green") centre_point = (int(W/2), int(H/2)) # Act ImageDraw.floodfill(im, centre_point, value) # Assert expected = "Tests/images/imagedraw_floodfill_"+mode+".png" im_floodfill = Image.open(expected) self.assert_image_equal(im, im_floodfill) # Test that using the same colour does not change the image ImageDraw.floodfill(im, centre_point, red) self.assert_image_equal(im, im_floodfill) # Test that filling outside the image does not change the image ImageDraw.floodfill(im, (W, H), red) self.assert_image_equal(im, im_floodfill) # Test filling at the edge of an image im = Image.new("RGB", (1, 1)) ImageDraw.floodfill(im, (0, 0), red) self.assert_image_equal(im, Image.new("RGB", (1, 1), red))
def test_floodfill_thresh(): # floodfill() is experimental # Arrange im = Image.new("RGB", (W, H)) draw = ImageDraw.Draw(im) draw.rectangle(BBOX2, outline="darkgreen", fill="green") centre_point = (int(W / 2), int(H / 2)) # Act ImageDraw.floodfill(im, centre_point, ImageColor.getrgb("red"), thresh=30) # Assert assert_image_equal_tofile(im, "Tests/images/imagedraw_floodfill2.png")
def DrawBalls(self, differentialMethod, step): # First, track the border for all balls and store # it to pos0 and edgePos. The latter will move along the border, # pos0 stays at the initial coordinates. for ball in self.balls: ball.pos0 = self.trackTheBorder(ball.pos + 1j) if ball.pos0 == None: ball.tracking = False else: ball.edgePos = ball.pos0 ball.tracking = True # print "Done with tracking" loopIndex = 0 while loopIndex < 200: loopIndex += 1 for ball in self.balls: if not ball.tracking: continue # store the old coordinates old_pos = ball.edgePos # walk along the tangent, using chosen differential method ball.edgePos = differentialMethod(ball.edgePos, step, self.calcTangent) # correction step towards the border ball.edgePos, tmp = self.stepOnceTowardsBorder(ball.edgePos) draw = ImageDraw.Draw(self.image) draw.line((old_pos.real, old_pos.imag, ball.edgePos.real, ball.edgePos.imag), fill=self.color) del draw # check if we've gone a full circle or hit some other # edge tracker for ob in self.balls: if ob.tracking: if (ob is not ball) and abs(ob.pos0 - ball.edgePos) < step: # or loopIndex > 3 ball.tracking = False tracking = 0 for ball in self.balls: if ball.tracking: tracking += 1 if tracking == 0: break for ball in self.balls: if ball.tracking: ball.pos = complex(round(ball.pos.real), round(ball.pos.imag)) ImageDraw.floodfill(self.image, (ball.pos.real, ball.pos.imag), self.color) # , self.color)
def test_floodfill(): red = ImageColor.getrgb("red") for mode, value in [("L", 1), ("RGBA", (255, 0, 0, 0)), ("RGB", red)]: # Arrange im = Image.new(mode, (W, H)) draw = ImageDraw.Draw(im) draw.rectangle(BBOX2, outline="yellow", fill="green") centre_point = (int(W / 2), int(H / 2)) # Act ImageDraw.floodfill(im, centre_point, value) # Assert expected = "Tests/images/imagedraw_floodfill_" + mode + ".png" with Image.open(expected) as im_floodfill: assert_image_equal(im, im_floodfill) # Test that using the same colour does not change the image ImageDraw.floodfill(im, centre_point, red) assert_image_equal(im, im_floodfill) # Test that filling outside the image does not change the image ImageDraw.floodfill(im, (W, H), red) assert_image_equal(im, im_floodfill) # Test filling at the edge of an image im = Image.new("RGB", (1, 1)) ImageDraw.floodfill(im, (0, 0), red) assert_image_equal(im, Image.new("RGB", (1, 1), red))
def mouseDoubleClickEvent(self, e): x = e.x() y = e.y() if image.getpixel((x, y)) == (255, 255, 255, 255): ImageDraw.floodfill(image, (x, y), (50, 205, 50, 255)) self.setPixmap(QPixmap.fromImage(ImageQt.ImageQt(image))) curTer = self.list.currentItem().text() if curTer not in config: config.update(OrderedDict({curTer: [(x, y)]})) else: config[curTer] += [(x, y)] item = self.list.currentItem() item.setFlags(item.flags() ^ Qt.ItemIsEditable)
def rand_fill(self, image): ''' Fill the center and edge of an image with two separate randomly picked colors. For airfoils, since the airfoil is an enclosed shape, this makes the background and cross section colors irrelevant to the regressor as signals :param image: PIL image to augment ''' width, height = image.size center = int(0.5 * width), int(0.5 * height) origin = 0, 0 ImageDraw.floodfill(image, xy=center, value=self.random_color()) ImageDraw.floodfill(image, xy=origin, value=self.random_color()) return image
def on_list_currentTextChanged(self, current): for ter in config: if ter == current: for (x, y) in config[ter]: ImageDraw.floodfill(image, (x, y), (50, 205, 50, 255)) self.pic.setPixmap( QPixmap.fromImage(ImageQt.ImageQt(image))) else: print(config) for (x, y) in config[ter]: if image.getpixel((x, y)) != (0, 0, 255, 255): ImageDraw.floodfill(image, (x, y), (0, 0, 255, 255)) self.pic.setPixmap( QPixmap.fromImage(ImageQt.ImageQt(image)))
def preProcessImg(): db = './public/cards/sourceImg' img_list = get_imlist(db, '.png') save = './public/cards/trainImg/' for i, img_path in enumerate(img_list): img_name = os.path.split(img_path)[1] image = Image.open(img_path).convert("RGBA") for key in color: new_image = Image.new("RGBA", image.size, color[key]) new_image.paste(image, (0, 0), image) new_image = new_image.convert('RGB') ImageDraw.floodfill(new_image, (0, 0), (136, 97, 148), thresh=0) new_image.save(save + key + img_name[:-4] + ".jpg", "JPEG")
def grid(res, gridres): res = res tile_size = gridres origin = [0, 0] x = 0 y = 0 im = Image.open("test.png") while origin[1] < res[1]: while origin[0] < res[0]: if origin[0] < res[0]: a = [origin[0], origin[1]] b = [x+tile_size, y+2*tile_size] c = [x, y+4*tile_size] d = [x+4*tile_size, y] e = [x+3*tile_size, y+2*tile_size] f = [x+4*tile_size, y+4*tile_size] g = [x+6*tile_size, y] h = [x+6*tile_size, y+4*tile_size] center0 = [x, y+1.5*tile_size] center1 = [x+2*tile_size, y+1.5*tile_size] pointa = (a[0]), (a[1]) pointb = (origin[0]+b[0]), (origin[1]+b[1]) pointc = (origin[0]+c[0]), (origin[1]+c[1]) pointd = (origin[0]+d[0]), (origin[1]+d[1]) pointe = (origin[0]+e[0]), (origin[1]+e[1]) pointf = (origin[0]+f[0]), (origin[1]+f[1]) pointg = (origin[0]+g[0]), (origin[1]+g[1]) pointh = ((origin[0]+h[0]), (origin[1]+h[1])) pointcenter1 = (origin[0] + center1[0], (origin[1] + center1[1])) pointcenter0 = (origin[0] + center0[0], (origin[1] + center0[1])) lines = [pointa, pointb, pointc, pointb, pointe, pointd, pointg, pointd, pointe, pointf, pointh] draw = ImageDraw.Draw(im) draw.line(lines, fill="Black", width=1) ImageDraw.floodfill(im, xy=pointcenter1, value=(255, 255, 255, 255)) ImageDraw.floodfill(im, xy=pointcenter0, value=(0, 0, 0, 255)) origin = pointg else: z = origin[1] z += 4*tile_size origin = [0, z] else: im.save("test.png", "PNG") print("Done")
def test_floodfill_not_negative(): # floodfill() is experimental # Test that floodfill does not extend into negative coordinates # Arrange im = Image.new("RGB", (W, H)) draw = ImageDraw.Draw(im) draw.line((W / 2, 0, W / 2, H / 2), fill="green") draw.line((0, H / 2, W / 2, H / 2), fill="green") # Act ImageDraw.floodfill(im, (int(W / 4), int(H / 4)), ImageColor.getrgb("red")) # Assert assert_image_equal_tofile(im, "Tests/images/imagedraw_floodfill_not_negative.png")
def color(): data = list(image.getdata()) real_data = [] for i in range(int(len(data) / (cwd + 1))): x = [] for j in range(cwd): x.append(data[j]) real_data.append(x) colors = [(255, 0, 0), (0, 0, 255), (255, 255, 0)] for i in range(randint(1, 5)): x = randint(1, cwd) y = randint(1, cht) ImageDraw.floodfill(image, (x, y), choice(colors), (0, 0, 0))
async def handler(req): lang = 'en' for i in req.query_args: if i[0] == 'lang': lang = str(i[1]).lower() if lang != "es-419": lang = "en" color = (255, 255, 0) seasonend = "2020-12-01T13:00:00Z" seasonstart = "2020-08-27T13:00:00Z" # daysleft = int((dp.parse(seasonend).timestamp()-datetime.utcnow().timestamp())/86400) daysgone = int( (datetime.utcnow().timestamp() - dp.parse(seasonstart).timestamp()) / 86400) seasonlen = int( (dp.parse(seasonend).timestamp() - dp.parse(seasonstart).timestamp()) / 86400) finalim = Image.open("API/v1/br/progress/new.png") im = Image.open('Cache/progress.png').convert('RGB') draw = ImageDraw.Draw(im) x, y, diam = (590 / 100) * int((seasonlen / 100) * daysgone), 8, 34 draw.ellipse([x, y, x + diam, y + diam], fill=color) ImageDraw.floodfill(im, xy=(14, 24), value=color, thresh=40) try: draw = ImageDraw.Draw(finalim) if lang == "es-419": text = f"Progreso Temporada 4 de Fortnite: {int((daysgone / 100 * seasonlen))}%" else: text = f"Fortnite Season 4 - {int((daysgone / 100) * seasonlen)}% over" BurbankBigCondensed = ImageFont.truetype( f"assets/Fonts/BurbankBigCondensed-Black.otf", 45) textWidth = BurbankBigCondensed.getsize(text)[0] Middle = int((finalim.width - textWidth) / 2) draw.text((Middle, 13), text, color, font=BurbankBigCondensed) except: traceback.print_exc() finalim.paste(im, (89, 73)) finalim.save('cdn/current/progress.png') return await sanic.response.file(f'cdn/current/progress.png')
def test_floodfill_border(): # floodfill() is experimental # Arrange im = Image.new("RGB", (W, H)) draw = ImageDraw.Draw(im) draw.rectangle(BBOX2, outline="yellow", fill="green") centre_point = (int(W / 2), int(H / 2)) # Act ImageDraw.floodfill( im, centre_point, ImageColor.getrgb("red"), border=ImageColor.getrgb("black"), ) # Assert assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill2.png"))
def test_floodfill_border(): # Arrange im = Image.new("RGB", (w, h)) draw = ImageDraw.Draw(im) draw.rectangle(bbox2, outline="yellow", fill="green") centre_point = (int(w / 2), int(h / 2)) # Act ImageDraw.floodfill(im, centre_point, ImageColor.getrgb("red"), border=ImageColor.getrgb("black")) del draw # Assert assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill2.png"))
def get_bw_connected_components_map(img, image): fill_mask = img.copy() fill_image = fill_mask.load() connected_components_map = numpy.zeros(fill_mask.size, dtype=int) component_number = 1 for x in range(0, fill_mask.size[0]): for y in range(0, fill_mask.size[1]): if fill_image[x, y] == 255: ImageDraw.floodfill(fill_mask, (x, y), 128) for i in range(0, connected_components_map.shape[0]): for j in range(0, connected_components_map.shape[1]): if fill_image[i, j] == 128: connected_components_map[i, j] = component_number fill_image[i, j] = 0 component_number += 1 return connected_components_map
def test_floodfill_thresh(self): # floodfill() is experimental # Arrange im = Image.new("RGB", (W, H)) draw = ImageDraw.Draw(im) draw.rectangle(BBOX2, outline="darkgreen", fill="green") centre_point = (int(W/2), int(H/2)) # Act ImageDraw.floodfill( im, centre_point, ImageColor.getrgb("red"), thresh=30) # Assert self.assert_image_equal( im, Image.open("Tests/images/imagedraw_floodfill2.png"))
def genLetter(xsize, ysize, character='Y', blur=2): fontsize = min(xsize, ysize) # fontsize = int(boxsize * 1.1) img = Image.new('RGB', (xsize, ysize), color=(255, 255, 255)) # get a font # character = 'P' # font = ImageFont.truetype("/System/Library/Fonts/Keyboard.ttf", fontsize) font = ImageFont.truetype("/System/Library/Fonts/Geneva.dfont", fontsize) width, height = font.getsize(character) x = int((xsize - width) / 2) y = int( (ysize - height * 1.3) / 2 ) # Need to adjust for font height: https://websemantics.uk/articles/font-size-conversion/ d = ImageDraw.Draw(img) d.text((x, y), character, fill=(0, 0, 0), font=font) # Add the text. # Blur the image. if blur > 0: img = img.filter(ImageFilter.BoxBlur(blur)) img = img.filter(ImageFilter.SMOOTH_MORE) # Flood file for masking. ImageDraw.floodfill( img, xy=(0, 0), value=(255, 0, 255), thresh=200 ) # https://stackoverflow.com/questions/46083880/fill-in-a-hollow-shape-using-python-and-pillow-pil # Fill in holes. n = np.array(img) n[(n[:, :, 0:3] != [255, 0, 255]).any(2)] = [0, 0, 0] # Revert all artifically filled magenta pixels to white n[(n[:, :, 0:3] == [255, 0, 255]).all(2)] = [255, 255, 255] img = Image.fromarray(n) img = img.convert('L') # Bridson_Common.logDebug(__name__, img.size) n = np.array(img) n = np.reshape(n, img.size) # Bridson_Common.logDebug(__name__, np.shape(n)) # Bridson_Common.logDebug(__name__, n) n = 255 - n # Need to flip the bits. The Freeman chain code generator requires the letter portion to have a value of 255 instead of 0. return (n)
def floodFill(canvas, origImage, edgeImage, color, filledImage=None): (width, height) = origImage.size edgePixels = edgeImage.load() fillRegionCoords = [] temporaryFill = (100,100,100) for x in xrange(width): for y in xrange(height): if (edgePixels[x, y] == color): fillRegionCoords += [(x,y)] ImageDraw.floodfill(edgeImage, (x,y), temporaryFill) #fill temporarily to make sure fillRegionCoords does not have #multiple coordinates that would fill the same region if (filledImage == None): filledImage = Image.open(canvas.data.edgeImageFile) for (x,y) in fillRegionCoords: fillColor = regionColor(origImage, filledImage, (x,y)) ImageDraw.floodfill(filledImage, (x,y), fillColor) return filledImage
def apply(self, image): for val in self.mod['remove']: edge = Op.detectEdge(val.img) Op.updateOriginalImage(image, edge) for val in self.mod['add']: image = Op.addImage(image, val.img) for val in self.mod['fill']: if val is Shape.SOLID: image = Shape.fill(image) for val in self.mod['transform']: if val is not None: image = image.transpose(val) for val in self.mod['rotate']: image = image.rotate(val) image = ImageOps.expand(image, border=2, fill=Const.BLACK_VALUE) ImageDraw.floodfill(image, xy=(0, 0), value=Const.WHITE_VALUE) image = ImageOps.crop(image, border=2) return image
def get_progress(self, percents: int): #percents : % of 100 size = (480, 32) im = Image.open('progress.png').convert('RGB').resize((500, 32)) draw = ImageDraw.Draw(im) color = (98, 211, 245) x, y, diam = int(size[0] / 100 * percents), 5, 21 if x == 0: pass else: half = diam // 2 if x < half + 11: x = half elif x >= half + 11: x -= half draw.ellipse([x, y, x + diam, y + diam], fill=color) ImageDraw.floodfill(im, xy=(11, 18), value=color, thresh=40) return im
def drawterritory(t, color=None): """Draw an entire territory (will draw in color provided, default is owning player's color)""" terr = territories[str(riskboard.territories[t].name)] #Create colored version of the image canvas.delete(terr.name) if len(backcolors) > 0 and current_state.owners[t] is not None: for fp in terr.floodpoints: if color: ImageDraw.floodfill(terr.photo, fp, color) else: ImageDraw.floodfill(terr.photo, fp, hex_to_rgb(backcolors[current_state.owners[t]])) terr.currentimage = ImageTk.PhotoImage(terr.photo) canvas.create_image(terr.x, terr.y, anchor=Tkinter.NW, image=terr.currentimage, tags=(terr.name,)) drawarmy(t, 1)
def test_floodfill_border(self): # floodfill() is experimental # Arrange im = Image.new("RGB", (w, h)) draw = ImageDraw.Draw(im) draw.rectangle(bbox2, outline="yellow", fill="green") centre_point = (int(w/2), int(h/2)) # Act ImageDraw.floodfill( im, centre_point, ImageColor.getrgb("red"), border=ImageColor.getrgb("black")) del draw # Assert self.assert_image_equal( im, Image.open("Tests/images/imagedraw_floodfill2.png"))
def getShapeCoordiantes(self, image): """Counts the number of shapes in the image""" image = image.filter( ImageFilter.EDGE_ENHANCE).convert('1').convert('RGB') labels = [] coordinates = [] for x in range(image.width): for y in range(image.height): if image.getpixel((x, y)) not in labels: color = self.generateColor() while tuple(color) in labels: color = self.generateColor() ImageDraw.floodfill(image, (x, y), tuple(color)) labels.append(tuple(color)) coordinates.append({"coor": (x, y), "label": tuple(color)}) return coordinates, image
def main(width, height): flood = Image.new('RGB', (width, height), BLACK) # Create randomly generated walls for x in range(width): for y in range(height): flood.putpixel((x, y), BLACK if random.random() < 0.15 else WHITE) # Create borders for x in range(width): for y in range(height): if x in {0, width - 1} or y in {0, height - 1}: flood.putpixel((x, y), BLACK) # floodfill(50, 25, RED, flood) width, height = flood.size center = (int(0.5 * width), int(0.5 * height)) color = (255, 255, 0, 255) ImageDraw.floodfill(flood, xy=center, value=color, thresh=0) flood.show()
def catDraw(self, data, key, color): taille = len(data[key]) x = 880 y = 80 * (taille // 10 + 1) out = Image.new("RGB", (x, y)) cat = Image.new("RGB", (80, y)) ImageDraw.floodfill(cat, (0, 0), color) catD = ImageDraw.Draw(cat) textFormat = "" for j in range(0, len(key)): if key[j] == "-": textFormat += " " else: textFormat += key[j] if (j + 1) % 11 == 0: textFormat += "\n" catD.multiline_text((5, 5), textFormat, fill=(0, 0, 0), align="center") out.paste(cat, (0, 0)) for i in range(len(data[key])): try: headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/41.0.2228.0 Safari/537.3" } fd = urllib.request.Request(url=data[key][i], headers=headers) image_file = urllib.request.urlopen(fd) im = Image.open(image_file) im.thumbnail((80, 80)) except Exception: textFormat = "" for j in range(0, len(data[key][i])): textFormat += (data[key][i][j]) if (j + 1) % 11 == 0: textFormat += "\n" im = Image.new("RGB", (80, 80)) d = ImageDraw.Draw(im) d.multiline_text((5, 5), textFormat) out.paste(im, ((i * 80) % 800 + 80, 80 * (i // 10))) return out
def fill(self, x, y): ''' self.img[y][x] = 150 # self.count += 1 # print('{}'.format(self.count)) if self.img[y - 1][x] == 0: self.fill(x, y - 1) if self.img[y][x - 1] == 0: self.fill(x - 1, y) if self.img[y + 1][x] == 0: self.fill(x, y + 1) if self.img[y][x + 1] == 0: self.fill(x + 1, y) self.count += 1 print('{}'.format(self.count)) ''' self.img = Image.open('./img.png') print(self.img) ImageDraw.floodfill(self.img, (x, y), (255, 0, 0), border=None)
def test_floodfill_border(): # floodfill() is experimental if hasattr(sys, 'pypy_version_info'): # Causes fatal RPython error on PyPy skip() # Arrange im = Image.new("RGB", (w, h)) draw = ImageDraw.Draw(im) draw.rectangle(bbox2, outline="yellow", fill="green") centre_point = (int(w/2), int(h/2)) # Act ImageDraw.floodfill( im, centre_point, ImageColor.getrgb("red"), border=ImageColor.getrgb("black")) del draw # Assert assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill2.png"))
def checkRotation(self, shapeA, shapeB): ops = [45, -45, 125, -125] for op in ops: modifiedShape = ImageOps.expand( shapeA.img, border=100, fill=Const.WHITE_VALUE ) # shape will get cut off when rotates if it is close to the border modifiedShape = modifiedShape.rotate(op) modifiedShape = ImageOps.expand(modifiedShape, border=2, fill=Const.BLACK_VALUE) ImageDraw.floodfill(modifiedShape, xy=(0, 0), value=Const.WHITE_VALUE) modifiedShape = ImageOps.crop(modifiedShape, border=102) if Op.isHistSimilar(modifiedShape, shapeB.img, shouldCrop=True, p=False): return op return None
def imfill(arr, edge): """Fill holes in images. NOTE: dtype of input array will be temporarily converted uint8! This is because PIL's fromarray function works only with numpy arrays of data type 'uint8'. This may cause some data losses, so proceed with caution! Input: arr -- a numpy.array to be floodfilled edge -- a value of edges """ # using arr.astype to preserve array's dtype, as fromarray requires # array whose dtype is uint8 img = Image.fromarray(arr.astype('uint8')) # read-only aimg = img.copy() ImageDraw.floodfill(aimg, (0,0), edge, edge) invimg = ImageChops.invert(aimg) invarr = asarray(invimg) arr[invarr==255] = edge return arr
def test_floodfill_border(): # floodfill() is experimental if hasattr(sys, 'pypy_version_info'): # Causes fatal RPython error on PyPy skip() # Arrange im = Image.new("RGB", (w, h)) draw = ImageDraw.Draw(im) draw.rectangle(bbox2, outline="yellow", fill="green") centre_point = (int(w / 2), int(h / 2)) # Act ImageDraw.floodfill(im, centre_point, ImageColor.getrgb("red"), border=ImageColor.getrgb("black")) del draw # Assert assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill2.png"))
def printbar(salary, upperbound): im = Image.open('progress.png').convert('RGB') draw = ImageDraw.Draw(im) # Cyan-ish fill colour color=(98,211,245) n = upperbound ca = salary x_n = 600 # Draw circle at right end of progress bar x, y, diam = ca*x_n/n, 8, 34 draw.ellipse([x,y,x+diam,y+diam], fill=color) # Flood-fill from extreme left of progress bar area to behind circle ImageDraw.floodfill(im, xy=(14,24), value=color, thresh=40) draw.text((5,20), "0", fill=(255,255,0)) draw.text((x+20,20), str(ca), fill=(255,255,0)) draw.text((600,20), str(n), fill=(255,255,0)) # Save result im.save('fig1.png')
def ocr_outline_font(name_img): # gets text with outline font from an image # filter out font img = cv2.inRange(name_img, np.array([100, 100, 100]), np.array([255, 255, 255])) img = _cv_to_pil(img) # fill background point_inside_digit = (0, 0) ImageDraw.floodfill(img, point_inside_digit, ImageColor.getrgb("black"), thresh=200) # invert img = _pil_to_cv(img) img = cv2.inRange(img, np.array([0, 0, 0]), np.array([50, 50, 50])) img = _cv_to_pil(img) # apply image to string return pytesseract.image_to_string(img).strip()
def solve_four_color(im, g): """4色問題を解く""" from pulp import LpProblem, LpVariable, LpBinary, lpSum, lpDot, value r4 = range(4) m = LpProblem() # 数理モデル # エリアiを色jにするかどうか v = { i: [LpVariable("v%d_%d" % (i, j), cat=LpBinary) for j in r4] for i in g.nodes() } for i in g.nodes(): m += lpSum(v[i]) == 1 for i, j in g.edges(): for k in r4: m += v[i][k] + v[j][k] <= 1 m.solve() co = [(97, 132, 219), (228, 128, 109), (255, 241, 164), (121, 201, 164)] # 4色 rr = {k: int(value(lpDot(r4, w))) for k, w in v.items()} # 結果 for y, x in product(range(im.height - 1), range(im.width - 1)): c = im.getpixel((x, y)) if c[:2] == (0, 1) and c[2] in rr: # エリアならば、結果で塗る ImageDraw.floodfill(im, (x, y), co[rr[c[2]]])
def illustrate(self, shield_design, image): """ Draws a shield by taking the colours in the design and applying them to two halves of an image. """ fur = ImageColor.getrgb("#%s" % shield_design["fur"]["hex"]) tincture = ImageColor.getrgb("#%s" % shield_design["tincture"]["hex"]) ImageDraw.floodfill(image, (116, 67), fur) ImageDraw.floodfill(image, (253, 77), tincture) ImageDraw.floodfill(image, (144, 201), tincture) ImageDraw.floodfill(image, (214, 198), fur) return image
def identify_objects(self): im = copy.deepcopy(self.image) width, height = im.size dark_fill_val = 1 light_fill_val = 254 for x in range(width): for y in range(height): xy = (x, y) l_val = im.getpixel(xy) if l_val == 0: ImageDraw.floodfill(im, xy, dark_fill_val) self.objects.append(Object(xy, dark_fill_val)) dark_fill_val += 1 elif l_val == 255: ImageDraw.floodfill(im, xy, light_fill_val) light_fill_val -= 1 else: for obj in self.objects: if obj.l_val == l_val: obj.add_pixel(xy) break
def drawterritory(t, shaded): """Draw an entire territory (possibly shaded)""" risknetwork.draw_territory(t, shaded) terr = territories[t.name] #Create colored version of the image canvas.delete(terr.name) #print 'Drawing territory: ', t.name if hasattr(t.player, 'backcolor'): for fp in terr.floodpoints: #print 'Flood-filling', terr.name, ' territory' ImageDraw.floodfill(terr.photo, fp, hex_to_rgb(t.player.backcolor)) #print 'Saving images' terr.shadedimage = ImageTk.PhotoImage(terr.photo.point(lambda x:x * 0)) terr.currentimage = ImageTk.PhotoImage(terr.photo) if shaded: canvas.create_image(terr.x, terr.y, anchor=Tkinter.NW, image=terr.shadedimage, tags=(terr.name,)) else: canvas.create_image(terr.x, terr.y, anchor=Tkinter.NW, image=terr.currentimage, tags=(terr.name,)) drawarmy(riskengine.territories[terr.name], 1)
def test_floodfill(self): # Arrange im = Image.new("RGB", (W, H)) draw = ImageDraw.Draw(im) draw.rectangle(BBOX2, outline="yellow", fill="green") centre_point = (int(W/2), int(H/2)) red = ImageColor.getrgb("red") im_floodfill = Image.open("Tests/images/imagedraw_floodfill.png") # Act ImageDraw.floodfill(im, centre_point, red) # Assert self.assert_image_equal(im, im_floodfill) # Test that using the same colour does not change the image ImageDraw.floodfill(im, centre_point, red) self.assert_image_equal(im, im_floodfill) # Test that filling outside the image does not change the image ImageDraw.floodfill(im, (W, H), red) self.assert_image_equal(im, im_floodfill)
shortsizes = [(640, 480, 126)] masked_file = r"F:\Documents\Python\heroclicker\source\masked_final.bmp" masked = Image.open(masked_file) SaveDirectory = r'F:\Documents\Python\heroclicker\clean_fish' cleanlist = os.listdir(SaveDirectory) for desired in sortedsizes: output = Image.new(masked.mode, (desired[0], desired[1])) output.putpixel((0, 0), (255,255,255)) ImageDraw.floodfill(image=output, xy=(0, 0), value=(255, 255, 255)) width = int(desired[0]/clickable[0] + .5) height = int(desired[1]/clickable[1] + .5) total = width * height if total > limit: reuse = total / limit else: reuse = 0 print("Resolution:", str(desired[0]) + "x" + str(desired[1]), "width:", width, "Height:", height, "Clickables:", width*height, "reuse:", str(reuse)[:3]) currentx = 0 currenty = 0 fishcounter = 0 while True: if fishcounter == len(cleanlist): fishcounter = 0
def _draw_fill(self, image, d, key, percentage): color = self._color(percentage) for current_key, (cx, cy) in d: if current_key == key: ImageDraw.floodfill(image, (cx, cy), color)
# Random percolation cluster fractals # FB - 201003243 from PIL import Image from PIL import ImageDraw import random imgx = 512 imgy = 512 image = Image.new("RGB", (imgx, imgy)) maxIt = imgx * imgy / 1.25 for i in range(maxIt): x = random.randint(0, imgx - 1) y = random.randint(0, imgy - 1) r = random.randint(1, 255) g = random.randint(1, 255) b = random.randint(1, 255) r2 = random.randint(1, 255) g2 = random.randint(1, 255) b2 = random.randint(1, 255) image.putpixel((x, y), (r, g, b)) ImageDraw.floodfill(image, (x, y), (r2, g2, b2), (0, 0, 0)) image.save("percolation.png", "PNG")
""" Created on Oct 13, 2017 Used to answer this question: https://stackoverflow.com/a/46736330/1469465 @author: physicalattraction """ from PIL import ImageDraw from utils import save_img, open_img, print_pil_version_info if __name__ == '__main__': image = open_img('star_transparent.png') width, height = image.size center = (int(0.5 * width), int(0.5 * height)) yellow = (255, 255, 0, 255) ImageDraw.floodfill(image, xy=center, value=yellow) save_img(image, 'star_yellow.png') print_pil_version_info()
from PIL import ImageColor, ImageDraw, Image import sys thingy2 = Image.open(sys.argv[1]) draw = ImageDraw.Draw(thingy2) floodedimage = ImageDraw.floodfill(thingy2, (1, 1), 1) del draw # write to stdout thingy2.save(sys.argv[2])
def createImage(width, height): imBytes = np.zeros((width, height, 3)) im = Image.frombytes(size = (width, height), data = imBytes, mode = "RGB") ImageDraw.floodfill(im, (0, 0), (255, 255, 255)) return im