Outline bounding box onto image `Patch`.
974313
def _draw_outline(o:Patch, lw:int):
    ""
    o.set_path_effects([patheffects.Stroke(
        linewidth=lw, foreground='black'), patheffects.Normal()])
538666
def arc(document, bounding_rect, start, extent, style):
	""
	(x1, y1, x2, y2) = bounding_rect
	import math
	
	cx = (x1 + x2)/2.0
	cy = (y1 + y2)/2.0

	rx = (x2 - x1)/2.0
	ry = (y2 - y1)/2.0
	
	start  = math.radians(float(start))
	extent = math.radians(float(extent))

	# from SVG spec:
	# http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
	x1 =  rx * math.cos(start) + cx
	y1 = -ry * math.sin(start) + cy # XXX: ry is negated here

	x2 =  rx * math.cos(start + extent) + cx
	y2 = -ry * math.sin(start + extent) + cy # XXX: ry is negated here

	if abs(extent) > math.pi:
		fa = 1
	else:
		fa = 0

	if extent > 0.0:
		fs = 0
	else:
		fs = 1
	
	path = []
	# common: arc
	path.append('M%s,%s' % (x1, y1))
	path.append('A%s,%s 0 %d %d %s,%s' % (rx, ry, fa, fs, x2, y2))
	
	if style == ARC:
		pass
	
	elif style == CHORD:
		path.append('z')

	else: # default: pieslice
		path.append('L%s,%s' % (cx, cy))
		path.append('z')

	return setattribs(document.createElement('path'), d = ''.join(path))
77968
def fill_buf(buf, i, img, shape):
    ''''''

    # grid height is a multiple of individual image height
    m = buf.shape[0]/shape[0]

    sx = (i%m)*shape[1]
    sy = (i//m)*shape[0]
    sx = int(sx)
    sy = int(sy)
    buf[sy:sy+shape[0], sx:sx+shape[1], :] = img
294364
function createMaskingClip() {
            if (isAnimated) {
                // We use a white rectangle to simulate the line drawing animation
                maskingRectangle = svg.append('rect')
                    .attr('class', 'masking-rectangle')
                    .attr('width', width)
                    .attr('height', height)
                    .attr('x', 0)
                    .attr('y', 0);

                maskingRectangle.transition()
                    .duration(animationDuration)
                    .ease(ease)
                    .attr('x', width)
                    .on('end', () => maskingRectangle.remove());
            }
        }
525506
def add_rect(img, box, color=None, thickness=1):
    
    if color is None:
        color = COL_GRAY

    box = box.to_int()
    cv.rectangle(img, box.top_left(), box.bottom_right(), color, thickness)
263201
def _update_mask(self, mask: np.ndarray, polygons: Iterable, separate_instances: bool = False) -> None:
        
        for i, p in enumerate(polygons):
            if isinstance(p, geometry.MultiPolygon):
                self._update_mask(mask=mask, polygons=p.geoms, separate_instances=True)
                continue
            elif not isinstance(p, geometry.Polygon):
                continue
            poly_area = Image.fromarray(np.zeros(mask.shape, dtype=np.uint8))
            holes = Image.fromarray(np.zeros(mask.shape, dtype=np.uint8))
            outline_color = 0 if separate_instances else 255
            ImageDraw.Draw(poly_area).polygon(p.exterior.coords, fill=255, outline=outline_color)
            for h in p.interiors:
                ImageDraw.Draw(holes).polygon(h.coords, fill=255, outline=255)
            mask[np.nonzero(np.array(poly_area, dtype=np.uint8))] = 255
            mask[np.nonzero(np.array(holes, dtype=np.uint8))] = 0
688403
public static void renderStitching( BufferedImage imageA, BufferedImage imageB ,
										Homography2D_F64 fromAtoB )
	{
		// specify size of output image
		double scale = 0.5;

		// Convert into a BoofCV color format
		Planar<GrayF32> colorA =
				ConvertBufferedImage.convertFromPlanar(imageA, null, true, GrayF32.class);
		Planar<GrayF32> colorB =
				ConvertBufferedImage.convertFromPlanar(imageB, null,true, GrayF32.class);

		// Where the output images are rendered into
		Planar<GrayF32> work = colorA.createSameShape();

		// Adjust the transform so that the whole image can appear inside of it
		Homography2D_F64 fromAToWork = new Homography2D_F64(scale,0,colorA.width/4,0,scale,colorA.height/4,0,0,1);
		Homography2D_F64 fromWorkToA = fromAToWork.invert(null);

		// Used to render the results onto an image
		PixelTransformHomography_F32 model = new PixelTransformHomography_F32();
		InterpolatePixelS<GrayF32> interp = FactoryInterpolation.bilinearPixelS(GrayF32.class, BorderType.ZERO);
		ImageDistort<Planar<GrayF32>,Planar<GrayF32>> distort =
				DistortSupport.createDistortPL(GrayF32.class, model, interp, false);
		distort.setRenderAll(false);

		// Render first image
		model.set(fromWorkToA);
		distort.apply(colorA,work);

		// Render second image
		Homography2D_F64 fromWorkToB = fromWorkToA.concat(fromAtoB,null);
		model.set(fromWorkToB);
		distort.apply(colorB,work);

		// Convert the rendered image into a BufferedImage
		BufferedImage output = new BufferedImage(work.width,work.height,imageA.getType());
		ConvertBufferedImage.convertTo(work,output,true);

		Graphics2D g2 = output.createGraphics();

		// draw lines around the distorted image to make it easier to see
		Homography2D_F64 fromBtoWork = fromWorkToB.invert(null);
		Point2D_I32 corners[] = new Point2D_I32[4];
		corners[0] = renderPoint(0,0,fromBtoWork);
		corners[1] = renderPoint(colorB.width,0,fromBtoWork);
		corners[2] = renderPoint(colorB.width,colorB.height,fromBtoWork);
		corners[3] = renderPoint(0,colorB.height,fromBtoWork);

		g2.setColor(Color.ORANGE);
		g2.setStroke(new BasicStroke(4));
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2.drawLine(corners[0].x,corners[0].y,corners[1].x,corners[1].y);
		g2.drawLine(corners[1].x,corners[1].y,corners[2].x,corners[2].y);
		g2.drawLine(corners[2].x,corners[2].y,corners[3].x,corners[3].y);
		g2.drawLine(corners[3].x,corners[3].y,corners[0].x,corners[0].y);

		ShowImages.showWindow(output,"Stitched Images", true);
	}
814179
function (ctx, scale, layers, styles, zoom, minX, maxX, minY) {
  // background first
  styles.forEach(function(style) {
    if (cartoSelectorIsMatch(style, null, null, zoom)) {
      style.rules.forEach(function(rule) {
        if (rule.name === "background-color") {
          ctx.fillStyle = rule.value.toString();
        }
        else if (rule.name === "background-image") {
          if (!(rule.value instanceof Canvas.Image)) {
            var content = rule.value.toString();
            var img = new Canvas.Image();
            var imagePath = path.normalize(__dirname + "/../static/images/" + content);
            img.src = fs.readFileSync(imagePath);
            rule.value = img;
          }
        
          img = rule.value;
          ctx.fillStyle = ctx.createPattern(img, "repeat");
        }
      });
      ctx.fillRect(0,0,ctx.canvas.width, ctx.canvas.height);
    }
  });
  
  // create list of attachments (in order) so that we can walk through and render them together for each layer
  // TODO: should be able to do this as part of the processing stage
  var attachments = styles.reduce(function(attachmentList, style) {
    if (style.attachment !== "__default__" && attachmentList.indexOf(style.attachment) === -1) {
      attachmentList.push(style.attachment);
    }
    return attachmentList;
  }, []);
  attachments.push("__default__");
  
  layers.forEach(function(layer, i) {
    var source = layer.source;
    var features = layer.features || layer;
    
    attachments.forEach(function(attachment) {
      
      features.forEach(function(feature) {
        // get all the drawing rules for this attachment and feature
        var collapsedStyle = {};
        var instanceOrder = [];
        styles.forEach(function(style) {
          if (style.attachment === attachment && cartoSelectorIsMatch(style, feature, source, zoom)) {
            style.rules.forEach(function(rule) {
              if (!collapsedStyle[rule.instance]) {
                collapsedStyle[rule.instance] = {};
                instanceOrder.push(rule.instance);
              }
              if (!collapsedStyle[rule.instance].hasOwnProperty(rule.name)) {
                collapsedStyle[rule.instance][rule.name] = rule.value;
              }
            });
          }
        });
        
        var renderInstance = function(instanceName) {
          var instanceStyle = collapsedStyle[instanceName];
          
          ctx.save();
  
          var shouldFill = false,
              shouldStroke = false,
              shouldMark = false,
              shouldPoint = false,
              shouldText = false,
              dashedStroke = false;
          for (var key in instanceStyle) {
            var rawValue = instanceStyle[key],
                value = rawValue.toString();
            
            if (key === "background-color" || key === "polygon-fill") {
              ctx.fillStyle = value;
              shouldFill = true;
            }
            else if (key === "background-image" || key === "polygon-pattern-file") {
              if (rawValue) {
                ctx.fillStyle = ctx.createPattern(rawValue, "repeat");
                shouldFill = true;
              }
            }
            else if (key === "line-width") {
              ctx.lineWidth = parseInt(value);
            }
            else if (key === "line-color") {
              ctx.strokeStyle = value;
              shouldStroke = true;
            }
            else if (key === "line-opacity") {
              // handled at stroke time below
            }
            else if (key === "line-join") {
              ctx.lineJoin = value;
            }
            else if (key === "line-cap") {
              ctx.lineCap = value;
            }
            else if (key === "line-miterlimit") {
              ctx.miterLimit = value;
            }
            else if (key === "line-dasharray") {
              // TODO: dasharray support
              // console.log("Dasharray: ", value);
              var dashedStroke = value.split(",").map(parseFloat);
              // console.log("    now: ", dashArray);
              // ctx.dash = dashArray;
              // ctx.lineDash = dashArray;
            }
            else if (key === "polygon-opacity") {
              // handled at fill time below
            }
            else if (key === "line-pattern-file") {
              if (rawValue) {
                ctx.strokeStyle = ctx.createPattern(rawValue, "repeat");
                shouldStroke = true;
              }
            }
            else if (key.indexOf("marker") === 0) {
              shouldMark = true;
            }
            else if (key === "point-file") {
              shouldPoint = true;
            }
            else if (key === "text-name") {
              shouldText = true;
            }
          }
          
          if (shouldFill || shouldStroke || shouldMark || shouldPoint || shouldText) {
            ctx.beginPath();
            var shape = feature.geometry || feature;
            var coordinates = shape.coordinates;
            renderPath[shape.type].call(ctx, coordinates, scale);
            if (shouldFill) {
              ctx.globalAlpha = parseFloat(instanceStyle["polygon-opacity"]) || 1.0;
              var fillColor = instanceStyle["polygon-fill"];
              var fillPattern = instanceStyle["polygon-pattern-file"]
              if (fillColor) {
                ctx.fillStyle = fillColor.toString();
                ctx.fill();
              }
              if (fillPattern) {
                ctx.fillStyle = ctx.createPattern(fillPattern, "repeat");;
                ctx.fill();
              }
            }
            if (shouldStroke) {
              ctx.globalAlpha = parseFloat(instanceStyle["line-opacity"]) || 1.0;
              if (dashedStroke) {
                // since canvas doesn't yet have dashed line support, we have to draw a dashed path :(
                ctx.closePath();
                ctx.beginPath();
                renderDashedPath[shape.type].call(ctx, dashedStroke, coordinates);
              }
              ctx.stroke();
            }
            ctx.closePath();
            
            if (shouldMark) {
              if (instanceStyle["marker-file"]) {
                renderImage[shape.type].call(ctx, instanceStyle["marker-file"], coordinates);
              }
              else {
                // we only support the "ellipse" type
                // we only support circles, not ellipses right now :\
                var radius = instanceStyle["marker-width"] || instanceStyle["marker-height"];
                radius = (radius ? radius.value : 10) / 2;

                var shouldFillMarker = false;
                var shouldStrokeMarker = false;
                if (instanceStyle["marker-fill"]) {
                  ctx.fillStyle = instanceStyle["marker-fill"].toString();
                  shouldFillMarker = true;
                }
                if (instanceStyle["marker-line-color"]) {
                  ctx.strokeStyle = instanceStyle["marker-line-color"].toString();
                  shouldStrokeMarker = true;
                }
                if (instanceStyle["marker-line-width"]) {
                  var lineWidth = instanceStyle["marker-line-width"].value;
                  ctx.lineWidth = lineWidth;
                  shouldStrokeMarker = !!lineWidth;
                }
                
                ctx.beginPath();
                renderDot[shape.type].call(ctx, radius, coordinates);
                if (shouldFillMarker) {
                  ctx.fill();
                }
                if (shouldStrokeMarker) {
                  ctx.stroke();
                }
                ctx.closePath();
              }
            }
            
            if (shouldPoint && instanceStyle["point-file"]) {
              renderImage[shape.type].call(ctx, instanceStyle["point-file"], coordinates);
            }
            
            if (shouldText) {
              var text = instanceStyle["text-name"];
              if (text.is === "propertyLookup") {
                text = text.toString(feature);
              }
              
              if (text) {
                var textSize = (instanceStyle["text-size"] || "10").toString();
                var textFace = (instanceStyle["text-face-name"] || "sans-serif").toString();
                ctx.font = textSize + "px '" + textFace + "'";
                
                var textInfo = {
                  text: text
                };
                
                // offsetting
                textInfo.offset = {
                  x: instanceStyle["text-dx"] ? instanceStyle["text-dx"].value : 0,
                  y: instanceStyle["text-dy"] ? instanceStyle["text-dy"].value : 0
                };
                
                // vertical alignment
                var verticalAlign = instanceStyle["text-vertical-alignment"];
                if (verticalAlign && verticalAlign.value !== "auto") {
                  ctx.textBaseline = {
                    top: "top",
                    middle: "middle",
                    bottom: "alphabetic"
                  }[verticalAlign];
                }
                else {
                  ctx.textBaseline = textInfo.offset.y === 0 ? "middle" : (textInfo.offset.y < 0 ? "top" : "alphabetic");
                }
                
                // horizontal alignment
                var textHorizontalAlignment = instanceStyle["text-horizontal-alignment"];
                if (textHorizontalAlignment) {
                  ctx.textAlign = textHorizontalAlignment.toString();
                }
                else {
                  // default to center
                  ctx.textAlign = "center";
                }
                textInfo.align = ctx.textAlign;
                
                // text-transform
                var textTransform = instanceStyle["text-transform"];
                textTransform = textTransform && textTransform.toString();
                if (textTransform === "uppercase") {
                  textInfo.text = text.toUpperCase();
                }
                if (textTransform === "lowercase") {
                  textInfo.text = text.toLowerCase();
                }
                if (textTransform === "capitalize") {
                  textInfo.text = text.replace(/\b(\w)/g, function(match, character) {
                    return character.toUpperCase();
                  });
                }
                
                // text-placement
                var placement = instanceStyle["text-placement"];
                textInfo.placement = placement ? placement.toString() : "point";
                
                // TODO: text-placement-type (currently like "dummy")
                // TODO: text-align (this is alignment within the text *box*)
                // We don't have anything that generates a box right now, so we dont' support this
                
                if (instanceStyle["text-halo-fill"]) {
                  ctx.strokeStyle = instanceStyle["text-halo-fill"].toString();
                  if (instanceStyle["text-halo-radius"]) {
                    ctx.lineWidth = instanceStyle["text-halo-radius"].value * 2;
                  }
                  
                  // definitely DON'T leave this set to miter :P
                  ctx.lineJoin = "round";
                  textInfo.stroke = true;
                  renderText[shape.type].call(ctx, textInfo, coordinates);
                }
              
                if (instanceStyle["text-fill"]) {
                  ctx.fillStyle = instanceStyle["text-fill"].toString();
                }
                
                textInfo.stroke = false;
                renderText[shape.type].call(ctx, textInfo, coordinates);
              }
            }
          }
          
          ctx.restore();
        };
      
        instanceOrder.forEach(function(instanceName) {
          if (instanceName !== "__default__") {
            renderInstance(instanceName);
          }
        });
      
        if (collapsedStyle["__default__"]) {
          renderInstance("__default__");
        }
      
      });
      
    });
  });
}
143267
def draw_patchcollection(data, obj):
    
    content = []
    # Gather the draw options.
    try:
        ec = obj.get_edgecolor()[0]
    except IndexError:
        ec = None

    try:
        fc = obj.get_facecolor()[0]
    except IndexError:
        fc = None

    try:
        ls = obj.get_linestyle()[0]
    except IndexError:
        ls = None

    try:
        w = obj.get_linewidth()[0]
    except IndexError:
        w = None

    data, draw_options = mypath.get_draw_options(data, obj, ec, fc, ls, w)

    paths = obj.get_paths()
    for path in paths:
        data, cont, draw_options, is_area = mypath.draw_path(
            data, path, draw_options=draw_options
        )
        content.append(cont)

    if _is_in_legend(obj):
        # Unfortunately, patch legend entries need \addlegendimage in Pgfplots.
        tpe = "area legend" if is_area else "line legend"
        do = ", ".join([tpe] + draw_options) if draw_options else ""
        content += [
            "\\addlegendimage{{{}}}\n".format(do),
            "\\addlegendentry{{{}}}\n\n".format(obj.get_label()),
        ]
    else:
        content.append("\n")

    return data, content
1226675
def visual(title, X, activation):
    '''
    '''
    assert len(X.shape) == 4

    X = X.transpose((0, 2, 3, 1))
    if activation == 'sigmoid':
        X = np.clip((X)*(255.0), 0, 255).astype(np.uint8)
    elif activation == 'tanh':
        X = np.clip((X+1.0)*(255.0/2.0), 0, 255).astype(np.uint8)
    n = np.ceil(np.sqrt(X.shape[0]))
    buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8)
    for i, img in enumerate(X):
        fill_buf(buff, i, img, X.shape[1:3])
    cv2.imwrite('%s.jpg' % (title), buff)
1274317
def make_comparison_png(self, outpath=None, include_legend=False):
        
        from matplotlib.patches import Patch

        fig, axs = plt.subplots(ncols=2, sharex=True, sharey=True)

        three_color = self.make_three_color()
        axs[0].imshow(three_color)
        axs[0].set_axis_off()

        shape = self.thmap.shape
        axs[1].imshow(self.thmap,
                     origin='lower',
                     interpolation='nearest',
                     cmap=self.config.solar_cmap,
                     vmin=-1, vmax=len(self.config.solar_classes)-1)

        if include_legend:
            legend_elements = [Patch(facecolor=c, label=sc, edgecolor='k')
                               for sc, c in self.config.solar_colors.items()]
            axs[1].legend(handles=legend_elements, fontsize='x-small',
                         bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                         ncol=2, mode="expand", borderaxespad=0.)
        axs[1].set_xlim([0, shape[0]])
        axs[1].set_ylim([0, shape[0]])
        axs[1].set_aspect("equal")
        axs[1].set_axis_off()

        if outpath:
            fig.savefig(outpath, dpi=300,
                        transparent=True,
                        bbox_inches='tight',
                        pad_inches=0.)
            plt.close()
        else:
            plt.show()
126246
public static void boundImage( GrayF32 img , float min , float max ) {
		ImplPixelMath.boundImage(img,min,max);
	}
905691
def fixpix(data, mask, kind='linear'):
    """"""
    if data.shape != mask.shape:
        raise ValueError

    if not numpy.any(mask):
        return data

    x = numpy.arange(0, data.shape[0])
    for row, mrow in zip(data, mask):
        if numpy.any(mrow):  # Interpolate if there's some pixel missing
            valid = (mrow == numpy.False_)
            invalid = (mrow == numpy.True_)
            itp = interp1d(x[valid], row[valid], kind=kind, copy=False)
            row[invalid] = itp(x[invalid]).astype(row.dtype)
    return data
933492
def calculate_bounding_box_from_image(im, curr_page):
    """"""
    xMax, y_max = im.size
    bounding_box = im.getbbox() # note this uses ltrb convention
    if not bounding_box:
        #print("\nWarning: could not calculate a bounding box for this page."
        #      "\nAn empty page is assumed.", file=sys.stderr)
        bounding_box = (xMax/2, y_max/2, xMax/2, y_max/2)

    bounding_box = list(bounding_box) # make temporarily mutable

    # Compensate for reversal of the image y convention versus PDF.
    bounding_box[1] = y_max - bounding_box[1]
    bounding_box[3] = y_max - bounding_box[3]

    full_page_box = curr_page.mediaBox # should have been set already to chosen box

    # Convert pixel units to PDF's bp units.
    convert_x = float(full_page_box.getUpperRight_x()
                     - full_page_box.getLowerLeft_x()) / xMax
    convert_y = float(full_page_box.getUpperRight_y()
                     - full_page_box.getLowerLeft_y()) / y_max

    # Get final box; note conversion to lower-left point, upper-right point format.
    final_box = [
        bounding_box[0] * convert_x,
        bounding_box[3] * convert_y,
        bounding_box[2] * convert_x,
        bounding_box[1] * convert_y]

    return final_box
1019870
def qr2scad(stream):
    """"""

    img = Image.open(stream)

    # Convert to black and white 8-bit
    if img.mode != 'L':
        img = img.convert('L')

    # Invert color to get the right bounding box
    img = ImageOps.invert(img)

    bbox = img.getbbox()

    # Crop to only contain contents within the PDPs
    img = img.crop(bbox)

    width, height = img.size

    assert width == height,\
        'The QR code should be a square, but we found it to be %(w)sx%(h)s' % {
            'w': width,
            'h': height
        }

    qr_side = width

    # QR code superpixel size
    qr_pixel_size = (list(img.getdata()).index(0) / PDP_SIDE)

    # Get the resize factor from the PDP size
    new_size = qr_side / qr_pixel_size

    # Set a more reasonable size
    img = img.resize((new_size, new_size))
    qr_side = new_size

    img_matrix = img.load()

    result = 'module _qr_code_dot() {\n'
    result += '    cube([%(block_side)s, %(block_side)s, 1]);\n' % {
        'block_side': BLOCK_SIDE
    }
    result += '}\n'

    result += 'module qr_code() {\n'
    for row in range(qr_side):
        for column in range(qr_side):
            if img_matrix[column, row] != 0:
                result += '    translate([%(x)s, %(y)s, 0])' % {
                    'x': BLOCK_SIZE * column - qr_side / 2,
                    'y': -BLOCK_SIZE * row + qr_side / 2
                }
                result += ' _qr_code_dot();\n'
    result += '}\n'
    result += 'qr_code_size = %d;' % (qr_side)

    return result
1078742
function RoundImage(i, r, iw, ih, s) {
  var cv, c, r1 = parseFloat(r), l = max(iw, ih);
  cv = NewCanvas(iw, ih);
  if(!cv)
    return null;
  if(r.indexOf('%') > 0)
    r1 = l * r1 / 100;
  else
    r1 = r1 * s;
  c = cv.getContext('2d');
  c.globalCompositeOperation = 'source-over';
  c.fillStyle = '#fff';
  if(r1 >= l/2) {
    r1 = min(iw,ih) / 2;
    c.beginPath();
    c.moveTo(iw/2,ih/2);
    c.arc(iw/2,ih/2,r1,0,2*Math.PI,false);
    c.fill();
    c.closePath();
  } else {
    r1 = min(iw/2,ih/2,r1);
    RRect(c, 0, 0, iw, ih, r1, true);
    c.fill();
  }
  c.globalCompositeOperation = 'source-in';
  c.drawImage(i, 0, 0, iw, ih);
  return cv;
}
985752
def clip(self, px, py, w, h, img):
        ''''''
        sx = 0
        sy = 0

        if px < 0:
            sx = -px
            w += px
            px = 0
        if py < 0:
            sy = -py
            h += py
            py = 0
        if px+w > img.width:
            w = img.width - px
        if py+h > img.height:
            h = img.height - py
        return (px, py, sx, sy, w, h)