Exemplo n.º 1
0
func TestFov(t *testing.T) {
	mf := space.NewManifold()

	mf.SetPortal(space.Loc(10, 11, 1), space.Port(20, 20, 20))
	seen := map[image.Point]space.Location{}

	// Impassable barrier on every zone at x == 11
	blockFn := func(loc space.Location) bool { return loc.X == 11 }
	markFn := func(pt image.Point, loc space.Location) {
		seen[pt] = loc
	}

	fov := New(blockFn, markFn, mf)

	fov.Run(space.Loc(10, 10, 1), 4)

	if _, ok := seen[image.Pt(-2, 0)]; !ok {
		t.Fail()
	}

	if _, ok := seen[image.Pt(2, 0)]; ok {
		// Should be stopped by blockFn barrier
		t.Fail()
	}

	if loc, ok := seen[image.Pt(0, 2)]; ok {
		// This one should be through the portal.
		if loc.Zone != 20 {
			t.Fail()
		}
	} else {
		t.Fail()
	}
}
Exemplo n.º 2
0
func newEanCoordinateConverter(outerBound image.Rectangle, fm fontMeasurer) (*eanCoordinateConverter, error) {
	const rightMargin = digitBarSize
	const logicalWidth = 13*digitBarSize + startMarkerSize + endMarkerSize + centerMarkerSize + rightMargin
	scale := outerBound.Dx() / logicalWidth
	if scale <= 0 {
		return nil, errAreaTooSmall
	}
	xMargin := (outerBound.Dx() % logicalWidth) / 2
	fSize, fWidth, fHeight := fm(digitBarSize * scale)
	if digitBarSize*scale < fWidth {
		return nil, errFontTooBig
	}
	if outerBound.Dy() < fHeight*2 {
		return nil, errAreaTooSmall
	}
	return &eanCoordinateConverter{
		bound: image.Rectangle{
			Min: outerBound.Min.Add(image.Pt(xMargin, 0)),
			Max: outerBound.Max.Sub(image.Pt(xMargin, 0)),
		},
		fontDim:  image.Rect(0, 0, fWidth, fHeight),
		scale:    scale,
		fontSize: fSize,
	}, nil
}
Exemplo n.º 3
0
func Parse(spec ParseSpec, asciiMap string) (result *Chunk, err error) {
	var lines []string
	lines, err = preprocess(asciiMap)
	if err != nil {
		return
	}

	w, h := len(lines[0]), len(lines)
	result = &Chunk{[]Peg{}, map[image.Point]MapCell{}, image.Pt(w, h), &spec}
	edges := extractEdges(lines)
	for dir, edge := range edges {
		var pegs []Peg
		pegs, err = collectPegs(corner(Dir4(dir), result.dim), Dir4(dir), spec, edge)
		if err != nil {
			return
		}
		for _, peg := range pegs {
			result.pegs = append(result.pegs, peg)
		}
	}

	for y, line := range lines {
		for x, ch := range line {
			if !unicode.IsSpace(ch) {
				result.cells[image.Pt(x, y)] = MapCell(ch)
			}
		}
	}

	return
}
Exemplo n.º 4
0
func addLogo(profilePtr *image.Image, logo string, context appengine.Context) []byte {
	profileImage := *profilePtr
	destImage := image.NewRGBA(profileImage.Bounds())
	draw.Draw(destImage, destImage.Bounds(), profileImage, image.ZP, draw.Src)

	if logoImages, ok := THELOGOIMAGES[logo]; ok {
		randi := rand.Intn(len(logoImages))
		logoImage := logoImages[randi]

		offset := image.Pt(5, 5)
		if strings.HasPrefix(logo, "NLD-") {
			offset = image.Pt(0, 0)
		}

		start := profileImage.Bounds().Size()
		start = start.Sub(offset)
		start = start.Sub(logoImage.Bounds().Size())

		bounds := image.Rectangle{start, start.Add(logoImage.Bounds().Size())}
		draw.Draw(destImage, bounds, logoImage, image.ZP, draw.Over)

	} else {
		context.Errorf("Cannot load logoimage for %s", logo)
	}

	buffer := new(bytes.Buffer)
	err := png.Encode(buffer, destImage)
	check(err, context)

	return buffer.Bytes()
}
Exemplo n.º 5
0
// CorrBankStrideFFT computes the strided correlation of
// an image with a bank of filters.
// 	h_p[u, v] = (f corr g_p)[stride*u, stride*v]
func CorrBankStrideFFT(f *rimg64.Image, g *Bank, stride int) (*rimg64.Multi, error) {
	out := ValidSizeStride(f.Size(), g.Size(), stride)
	if out.X <= 0 || out.Y <= 0 {
		return nil, nil
	}
	// Compute strided convolution as the sum over
	// a stride x stride grid of small convolutions.
	grid := image.Pt(stride, stride)
	// But do not divide into a larger grid than the size of the filter.
	// If the filter is smaller than the stride,
	// then some pixels in the image will not affect the output.
	grid.X = min(grid.X, g.Width)
	grid.Y = min(grid.Y, g.Height)
	// Determine the size of the sub-sampled filter.
	gsub := image.Pt(ceilDiv(g.Width, grid.X), ceilDiv(g.Height, grid.Y))
	// The sub-sampled size of the image should be such that
	// the output size is attained.
	fsub := image.Pt(out.X+gsub.X-1, out.Y+gsub.Y-1)

	// Determine optimal size for FFT.
	work, _ := FFT2Size(fsub)
	// Cache FFT of image for convolving with multiple filters.
	// Re-use plan for multiple convolutions too.
	fhat := fftw.NewArray2(work.X, work.Y)
	ffwd := fftw.NewPlan2(fhat, fhat, fftw.Forward, fftw.Estimate)
	defer ffwd.Destroy()
	// FFT for current filter.
	ghat := fftw.NewArray2(work.X, work.Y)
	gfwd := fftw.NewPlan2(ghat, ghat, fftw.Forward, fftw.Estimate)
	defer gfwd.Destroy()
	// Allocate one array per output channel.
	hhat := make([]*fftw.Array2, len(g.Filters))
	for k := range hhat {
		hhat[k] = fftw.NewArray2(work.X, work.Y)
	}
	// Normalization factor.
	alpha := complex(1/float64(work.X*work.Y), 0)
	// Add the convolutions over channels and strides.
	for i := 0; i < grid.X; i++ {
		for j := 0; j < grid.Y; j++ {
			// Take transform of downsampled image given offset (i, j).
			copyStrideTo(fhat, f, stride, image.Pt(i, j))
			ffwd.Execute()
			// Take transform of each downsampled channel given offset (i, j).
			for q := range hhat {
				copyStrideTo(ghat, g.Filters[q], stride, image.Pt(i, j))
				gfwd.Execute()
				addMul(hhat[q], ghat, fhat)
			}
		}
	}
	// Take the inverse transform of each channel.
	h := rimg64.NewMulti(out.X, out.Y, len(g.Filters))
	for q := range hhat {
		scale(alpha, hhat[q])
		fftw.IFFT2To(hhat[q], hhat[q])
		copyRealToChannel(h, q, hhat[q])
	}
	return h, nil
}
Exemplo n.º 6
0
func (jw *JsonWed) ImportOverlays(wed *Wed) error {
	jw.Overlays = make([]jsonWedOverlay, 0)
	jw.TileIndices = make([]int, len(wed.TileIndices))
	for idx, overlay := range wed.Overlays {
		if overlay.Name.String() != "" {
			ov := jsonWedOverlay{}
			ov.Width = int(overlay.Width)
			ov.Height = int(overlay.Height)
			ov.Name = overlay.Name.String()
			ov.Flags = int(overlay.LayerFlags)

			ov.Tilemap = make([]jsonWedTilemap, len(wed.Tilemaps[idx]))
			for tmIdx, tilemap := range wed.Tilemaps[idx] {
				ov.Tilemap[tmIdx].Id = int(tilemap.TileIndexLookupIndex)
				ov.Tilemap[tmIdx].Count = int(tilemap.TileIndexLookupCount)
				ov.Tilemap[tmIdx].Alt = int(tilemap.AlternateTileIndex)
				ov.Tilemap[tmIdx].Flags = int(tilemap.Flags)
				ov.Tilemap[tmIdx].AnimSpeed = int(tilemap.AnimSpeed)
				ov.Tilemap[tmIdx].WFlags = int(tilemap.WFlags)
			}

			tisFile, err := os.Open(overlay.Name.String() + ".tis")
			if err != nil {
				return fmt.Errorf("unable to open overlay: %s %v", overlay.Name.String(), err)
			}
			defer tisFile.Close()

			cwd, err := os.Getwd()
			if err != nil {
				return fmt.Errorf("unable to get working directory: %v", err)
			}
			tis, err := OpenTis(tisFile, overlay.Name.String(), cwd)
			if err != nil {
				return fmt.Errorf("unable to open tis: %v", err)
			}
			ov.Tis = tis
			img := image.NewRGBA(image.Rect(0, 0, 64*ov.Width, 64*ov.Height))
			closedimg := image.NewRGBA(image.Rect(0, 0, 64*ov.Width, 64*ov.Height))
			for y := 0; y < int(ov.Height); y++ {
				for x := 0; x < int(ov.Width); x++ {
					tileNum := y*int(ov.Width) + x
					tileImg := tis.SubImage(tileNum)
					draw.Draw(img, image.Rect(x*64, y*64, x*64+64, y*64+64), tileImg, image.Pt(0, 0), draw.Src)
					if ov.Tilemap[tileNum].Alt != -1 {
						tileImg = tis.SubImage(ov.Tilemap[tileNum].Alt)
						draw.Draw(closedimg, image.Rect(x*64, y*64, x*64+64, y*64+64), tileImg, image.Pt(0, 0), draw.Src)
					}
				}
			}
			ov.BackgroundImg = img
			ov.ClosedImage = closedimg

			jw.Overlays = append(jw.Overlays, ov)
		}
	}
	for idx, ti := range wed.TileIndices {
		jw.TileIndices[idx] = int(ti)
	}
	return nil
}
Exemplo n.º 7
0
func TestFlag(t *testing.T) {
	if flagfn(nil) == nil {
		t.Errorf("nil func returned")
	}

	fs := flag.NewFlagSet("testcmd", flag.ContinueOnError)
	var r1, r2 *image.Rectangle
	r2 = &image.Rectangle{}
	def := image.Rectangle{Min: image.Pt(3, 4), Max: image.Pt(4, 6)} // 1x2+3+4
	r1 = defineFlag(fs, nil, "t1", def, "the first test")
	if r1 == nil {
		t.Errorf("defineFlag returned nil")
	}
	r2 = defineFlag(fs, r2, "t2", def, "the second test")
	if r1 == nil {
		t.Errorf("defineFlag returned nil")
	}
	if r2 != r2 { // pointers should be equal
		t.Errorf("defineFlag returned a different pointer")
	}
	err := fs.Parse([]string{"-t2=1x1+1+1"})
	if err != nil {
		t.Errorf("parse error: %v", err)
	}
	if *r1 != def {
		t.Errorf("r1: %#v", *r1)
	}
	if *r2 != image.Rect(1, 1, 2, 2) {
		t.Errorf("r2: %#v", r2)
	}
}
Exemplo n.º 8
0
func ScreenCapture() (*image.NRGBA, error) {
	args := captureCommand()
	cmd := exec.Command(args[0], args[1:]...)

	buf := &bytes.Buffer{}
	cmd.Stdout = buf
	if err := cmd.Run(); err != nil {
		return nil, err
	}
	data, err := decompressCapture(buf.Bytes())
	if err != nil {
		return nil, err
	}

	buf = bytes.NewBuffer(data)
	width := int32(0)
	height := int32(0)
	version := int32(0)

	if err := binary.Read(buf, binary.LittleEndian, &width); err != nil {
		return nil, err
	}
	if err := binary.Read(buf, binary.LittleEndian, &height); err != nil {
		return nil, err
	}
	if err := binary.Read(buf, binary.LittleEndian, &version); err != nil {
		return nil, err
	}

	stride := int(width * 4)
	rect := image.Rectangle{image.Pt(0, 0), image.Pt(int(width), int(height))}

	return &image.NRGBA{Pix: data[12:], Stride: stride, Rect: rect}, nil
}
Exemplo n.º 9
0
func Crop(img image.Image, width int, height int, padding int) (fimg draw.Image, err error) {
	// For now assume top left is bg color
	// future maybe avg outer rows of pixels
	bgcolor := img.At(img.Bounds().Min.X, img.Bounds().Min.Y)
	logoh, logow := height-2*padding, width-2*padding
	logorat := float32(logow) / float32(logoh)

	interior := findLogo(img, bgcolor)
	interior.Max = interior.Max.Add(image.Pt(1, 1))

	center := func(rect image.Rectangle) image.Point {
		return image.Point{(rect.Max.X - rect.Min.X) / 2, (rect.Max.Y - rect.Min.Y) / 2}
	}
	fimg = image.NewRGBA(image.Rect(0, 0, width, height))

	rc := center(fimg.Bounds())
	origrat := float32(interior.Dx()) / float32(interior.Dy())

	if logorat > origrat {
		logow = int(origrat * float32(logoh))
	} else {
		logoh = int(float32(logow) / origrat)
	}
	logoimg := Resize(img, interior, logow, logoh)

	logorect := image.Rect(0, 0, logoimg.Bounds().Dx(), logoimg.Bounds().Dy())
	logorect = logorect.Add(rc.Sub(image.Pt(logorect.Dx()/2, logorect.Dy()/2)))

	draw.Draw(fimg, fimg.Bounds(), &image.Uniform{bgcolor}, image.ZP, draw.Src)
	draw.Draw(fimg, logorect, logoimg, image.ZP, draw.Src)
	return
}
Exemplo n.º 10
0
func (h *Hud) drawHealth(bounds image.Rectangle) {
	heart := app.Cache().GetDrawable(util.SmallIcon(util.Items, 22))
	halfHeart := app.Cache().GetDrawable(util.SmallIcon(util.Items, 23))
	noHeart := app.Cache().GetDrawable(util.SmallIcon(util.Items, 24))
	shield := app.Cache().GetDrawable(util.SmallIcon(util.Items, 25))
	halfShield := app.Cache().GetDrawable(util.SmallIcon(util.Items, 26))

	pc, _ := h.world.Player.(entity.Stats)
	offset := bounds.Min
	for i := 0; i < pc.MaxHealth(); i += 2 {
		n := pc.Health() - i
		if n > 1 {
			heart.Draw(offset)
		} else if n > 0 {
			halfHeart.Draw(offset)
		} else {
			noHeart.Draw(offset)
		}
		offset = offset.Add(image.Pt(util.TileW, 0))
	}
	for i := 0; i < pc.Shield(); i += 2 {
		n := pc.Shield() - i
		if n > 1 {
			shield.Draw(offset)
		} else {
			halfShield.Draw(offset)
		}
		offset = offset.Add(image.Pt(util.TileW, 0))
	}
}
Exemplo n.º 11
0
func TestAssertNotEqual(t *testing.T) {
	AssertNotEqual(t, 2, 1)
	AssertNotEqual(t, "ABC", strings.ToLower("ABC"))
	AssertNotEqual(t, []byte("ABC"), bytes.ToLower([]byte("ABC")))
	AssertNotEqual(t, image.Pt(1, 2), image.Pt(2, 2))
	AssertNotEqual(t, image.Pt(1, 2), image.Rect(1, 2, 3, 4))
}
Exemplo n.º 12
0
func TestSideOverwrite(t *testing.T) {
	chunks := parseChunks(t, `
###
#..
#.#
#.|
###

###
..#
#|#

#|#
#.#
###

###
|.#
###
`)

	// Build an L-shaped room from the first two chunks.
	gen := New(chunks[0], '#')
	gen.AddChunk(gen.FittingChunks(gen.PegsAt(image.Pt(2, 1))[0], chunks)[0])

	// Add a chunk to south peg. The chunk that matches the peg but overwrites
	// the other door should be returned.
	fits := gen.FittingChunks(gen.PegsAt(image.Pt(2, 3))[0], chunks)
	if len(fits) != 1 {
		t.Error("Fitting chunks not found")
	}
}
Exemplo n.º 13
0
func main() {
	fmt.Println("ImgNet loading...")
	netSize := []int{3, 3}
	net := NewImgNet(netSize[0], netSize[1])

	imgOrig, err := imaging.Open("lena-colour.png")
	if err != nil {
		panic(err)
	}

	imgFiltered, err := imaging.Open("lena-colourdiff.png")
	if err != nil {
		panic(err)
	}

	targetImg, err := imaging.Open("lena-colour.png")
	if err != nil {
		panic(err)
	}

	fmt.Println("Teaching network.")
	for randcount := 0; randcount < 1000000; randcount++ {
		x := rand.Intn(imgOrig.Bounds().Dx()-netSize[0]) - netSize[0]/2
		y := rand.Intn(imgOrig.Bounds().Dy()-netSize[1]) - netSize[1]/2
		net.FF(image.Pt(x, y), &imgOrig)
		net.BP(image.Pt(x, y), &imgFiltered)
	}

	fmt.Println("Filtering image.")
	result := net.Filter(targetImg)
	imaging.Save(result, "output.png")

}
Exemplo n.º 14
0
func (phi SumPool) Apply(x *rimg64.Multi) (*rimg64.Multi, error) {
	if phi.Field.X <= 0 || phi.Field.Y <= 0 {
		err := fmt.Errorf("invalid field size: %v", phi.Field)
		return nil, err
	}
	if phi.Stride <= 0 {
		err := fmt.Errorf("invalid stride: %d", phi.Stride)
		return nil, err
	}
	size := image.Pt(
		ceilDiv(x.Width-phi.Field.X+1, phi.Stride),
		ceilDiv(x.Height-phi.Field.Y+1, phi.Stride),
	)
	y := rimg64.NewMulti(size.X, size.Y, x.Channels)
	for i := 0; i < y.Width; i++ {
		for j := 0; j < y.Height; j++ {
			for k := 0; k < x.Channels; k++ {
				// Position in original image.
				p := image.Pt(i, j).Mul(phi.Stride)
				var t float64
				for u := p.X; u < p.X+phi.Field.X; u++ {
					for v := p.Y; v < p.Y+phi.Field.Y; v++ {
						t += x.At(u, v, k)
					}
				}
				y.Set(i, j, k, t)
			}
		}
	}
	return y, nil
}
Exemplo n.º 15
0
func (vp *ViewPanel) Draw() {

	vp.Clear()

	// draw terrain
	if vp.g.Map != nil {
		for x, row := range vp.g.Map.Locations {
			for y, terr := range row {
				realpos := vp.cam.Transform(image.Pt(x, y))
				if true || vp.cam.ContainsWorldPoint(realpos) {
					c := terr.Glyph
					vp.SetCell(realpos.X, realpos.Y, c.Ch, c.Fg, c.Bg)
				}
			}
		}
	}

	for o := range vp.g.Objects.Chan() {
		if o.GetTag("visible") {
			realpos := vp.cam.Transform(image.Pt(o.GetPos()))
			g := o.GetGlyph()
			vp.SetCell(realpos.X, realpos.Y, g.Ch, g.Fg, g.Bg)
		}
	}

	vp.Buffered.Draw()
}
Exemplo n.º 16
0
func TestLoadConfig(t *testing.T) {
	var sampleFile = "../_template/furnace.toml"

	var answer = Config{
		Type:  "furnace",
		Image: "furnace.png",
		Crop:  image.Rect(7, 6, 168, 79),
		Slot: []image.Point{
			{56, 53},
			{56, 17},
			{116, 35},
		},
		Progress: []Progress{
			{
				Crop:  image.Rect(176, 0, 189, 13),
				Paste: image.Pt(57, 36),
			},
			{
				Crop:  image.Rect(176, 14, 24, 17),
				Paste: image.Pt(199, 30),
			},
		},
	}

	sample := sampleFile
	ans := answer
	if !reflect.DeepEqual(LoadConfig(sample), ans) {
		t.Error("toml convert error: not equal input and output \n", LoadConfig(sample), ans)
	}
}
Exemplo n.º 17
0
func (s *Sigil) cells(width int, data []byte) []image.Rectangle {
	width = width / (s.Rows + 1)
	cols := s.Rows/2 + s.Rows%2
	cells := cols * s.Rows
	res := make([]image.Rectangle, 0, s.Rows*s.Rows)
	padding := width / 2
	for i := 0; i < cells; i++ {
		if !s.fill(i, data) {
			continue
		}

		column := i / s.Rows
		row := i % s.Rows

		pt := image.Pt(padding+(column*width), padding+(row*width))
		rect := image.Rectangle{pt, image.Pt(pt.X+width, pt.Y+width)}
		if s.Rows%2 == 0 && column == cols-1 {
			// last/middle column, double width
			rect.Max.X += width
		}
		res = append(res, rect)

		if column < cols-1 {
			// add mirrored column
			rect.Min.X = padding + ((s.Rows - column - 1) * width)
			rect.Max.X = rect.Min.X + width
			res = append(res, rect)
		}
	}
	return res
}
Exemplo n.º 18
0
func (phi *MaxPool) Apply(x *rimg64.Multi) (*rimg64.Multi, error) {
	if phi.Field.X <= 0 || phi.Field.Y <= 0 {
		err := fmt.Errorf("invalid field size: %v", phi.Field)
		return nil, err
	}
	if phi.Stride <= 0 {
		err := fmt.Errorf("invalid stride: %d", phi.Stride)
		return nil, err
	}
	size := image.Pt(
		ceilDiv(x.Width-phi.Field.X+1, phi.Stride),
		ceilDiv(x.Height-phi.Field.Y+1, phi.Stride),
	)
	y := rimg64.NewMulti(size.X, size.Y, x.Channels)
	for i := 0; i < y.Width; i++ {
		for j := 0; j < y.Height; j++ {
			for k := 0; k < x.Channels; k++ {
				// Position in original image.
				p := image.Pt(i, j).Mul(phi.Stride)
				max := math.Inf(-1)
				for u := 0; u < phi.Field.X; u++ {
					for v := 0; v < phi.Field.Y; v++ {
						q := p.Add(image.Pt(u, v))
						max = math.Max(max, x.At(q.X, q.Y, k))
					}
				}
				y.Set(i, j, k, max)
			}
		}
	}
	return y, nil
}
Exemplo n.º 19
0
func draw(gen *chunk.Gen, pegIdx int, chunkIdx int) {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	min := image.Pt(math.MaxInt32, math.MaxInt32)
	for pt, _ := range gen.Map() {
		if pt.X < min.X {
			min.X = pt.X
		}
		if pt.Y < min.Y {
			min.Y = pt.Y
		}
	}

	min = min.Sub(image.Pt(4, 4))

	for pt, cell := range gen.Map() {
		nPegs := len(gen.PegsAt(pt))
		foreground := termbox.ColorWhite
		if len(gen.OpenPegs()) == 0 {
			foreground = termbox.ColorYellow
		}
		background := termbox.ColorBlack
		switch nPegs {
		case 0:
		case 1:
			background = termbox.ColorBlue
		case 2:
			background = termbox.ColorGreen
		default:
			background = termbox.ColorRed
		}
		screenPt := pt.Sub(min)
		termbox.SetCell(screenPt.X, screenPt.Y, rune(cell),
			foreground, background)
	}

	if pegIdx < len(gen.OpenPegs()) {
		fits := []chunk.OffsetChunk{}
		// Add the chunks that fit in the lattice
		for _, oc := range gen.FittingChunks(gen.OpenPegs()[pegIdx], chunks) {
			fits = append(fits, oc)
		}
		if len(fits) == 0 {
			gen.ClosePeg(gen.OpenPegs()[pegIdx])
		} else {
			oc := fits[chunkIdx%len(fits)]
			for y := oc.Bounds().Min.Y; y < oc.Bounds().Max.Y; y++ {
				for x := oc.Bounds().Min.X; x < oc.Bounds().Max.X; x++ {
					pt := image.Pt(x, y)
					screenPt := pt.Sub(min)
					if c, ok := oc.At(pt); ok {
						termbox.SetCell(screenPt.X, screenPt.Y, rune(c),
							termbox.ColorRed, termbox.ColorBlack)
					}
				}
			}
		}
	}

	termbox.Flush()
}
Exemplo n.º 20
0
func main() {

	// input files
	files := []string{"01.png", "02.png", "03.png"}

	// load images and make 100x100 thumbnails of them
	var images []image.Image
	for _, file := range files {
		img, err := imaging.Open(file)
		if err != nil {
			panic(err)
		}
		images = append(images, img)
	}

	n := neuro.NewNetwork([]int{3, 3, 3})

	for y := 0; y < images[0].Bounds().Dy(); y++ {
		for x := 0; x < images[0].Bounds().Dx(); x++ {
			imgR, imgG, imgB, _ := images[0].At(x, y).RGBA()
			r := float64(imgR) / 65535
			g := float64(imgG) / 65535
			b := float64(imgB) / 65535
			n.FeedForward([]float64{r, g, b})

			imgR2, imgG2, imgB2, _ := images[1].At(x, y).RGBA()
			r2 := float64(imgR2) / 65535
			g2 := float64(imgG2) / 65535
			b2 := float64(imgB2) / 65535
			n.BackPropagation([]float64{r2, g2, b2})
		}
	}

	m := image.NewRGBA(image.Rect(0, 0, 128, 128))
	for y := 0; y < images[2].Bounds().Dy(); y++ {
		for x := 0; x < images[2].Bounds().Dx(); x++ {
			imgR, imgG, imgB, _ := images[2].At(x, y).RGBA()
			r := float64(imgR) / 65535
			g := float64(imgG) / 65535
			b := float64(imgB) / 65535
			n.FeedForward([]float64{r, g, b})
			results := n.Results()
			c := color.RGBA{uint8(results[0] * 255), uint8(results[1] * 255), uint8(results[2] * 255), 255}
			m.Set(x, y, c)
		}
	}

	dst := imaging.New(256, 256, color.NRGBA{0, 0, 0, 0})
	dst = imaging.Paste(dst, images[0], image.Pt(0, 0))
	dst = imaging.Paste(dst, images[1], image.Pt(128, 0))
	dst = imaging.Paste(dst, images[2], image.Pt(0, 128))
	dst = imaging.Paste(dst, m, image.Pt(128, 128))

	// save the combined image to file
	err := imaging.Save(dst, "dst.jpg")
	if err != nil {
		panic(err)
	}
}
Exemplo n.º 21
0
Arquivo: main.go Projeto: ajhager/rog
func example() {
	if first {
		first = false
		for y := 0; y < height; y++ {
			for x := 0; x < width; x++ {
				if tmap[y][x] == '#' {
					pmap.Block(x, y, true)
				}
			}
		}
		movePlayer(23, 9)
	}

	if rog.Mouse().Left.Released {
		limit := image.Rect(0, 0, 40, 20)
		target := image.Pt(rog.Mouse().Cell.X, rog.Mouse().Cell.Y)
		path = rog.Path(level, limit, image.Pt(x, y), target)
	}

	switch rog.Key() {
	case 'k':
		movePlayer(x, y-1)
	case 'j':
		movePlayer(x, y+1)
	case 'h':
		movePlayer(x-1, y)
	case 'l':
		movePlayer(x+1, y)
	case rog.Esc:
		rog.Close()
	}

	for cy := 0; cy < pmap.Height(); cy++ {
		for cx := 0; cx < pmap.Width(); cx++ {
			rog.Set(cx, cy, nil, rog.Black, " ")
			if pmap.Look(cx, cy) {
				i := intensity(x, y, cx, cy, 20)
				if tmap[cy][cx] == '#' {
					rog.Set(cx, cy, nil, wall.Scale(i), "")
				} else {
					rog.Set(cx, cy, rog.Scale(1.5), floorc.Scale(i), "✵")
				}
			}
		}
	}
	rog.Set(x, y, lgrey, nil, "웃")

	for _, p := range path {
		if p.X != x || p.Y != y {
			rog.Set(p.X, p.Y, lgrey, nil, "*")
		}
	}

	runtime.ReadMemStats(&stats)
	rog.Fill(0, 0, rog.Width(), 1, lgrey, rog.Dodge(dgrey), ' ')
	rog.Set(0, 0, nil, nil, "%vFPS %vMB %vGC %vGR", rog.Fps(), stats.HeapAlloc/1000000, stats.NumGC, runtime.NumGoroutine())
	rog.Fill(0, height-1, rog.Width(), 1, lgrey, rog.Dodge(dgrey), ' ')
	rog.Set(0, height-1, nil, nil, "Pos: %v %v Cell: %v %v", rog.Mouse().Pos.X, rog.Mouse().Pos.Y, rog.Mouse().Cell.X, rog.Mouse().Cell.Y)
}
Exemplo n.º 22
0
func (c *eanCoordinateConverter) translateFont(x int) (rect image.Rectangle, fontSize int) {
	fontCellWidth := c.scale * digitBarSize
	fontXOffset := (fontCellWidth - c.fontDim.Dx()) / 2
	fontYOffset := c.bound.Dy() - c.fontDim.Dy()
	topLeft := c.bound.Min.Add(image.Pt(x*c.scale+fontXOffset, fontYOffset))
	bottomRight := topLeft.Add(image.Pt(c.fontDim.Dx(), c.fontDim.Dy()))
	return image.Rectangle{Min: topLeft, Max: bottomRight}, c.fontSize
}
Exemplo n.º 23
0
func mleft() {
	if !collide(image.Pt(pos.X-pcsz, pos.Y), piece) && !collide(image.Pt(pos.X-pcsz, pos.Y+pcsz-DY), piece) {
		undrawpiece()
		pos.X -= pcsz
		drawpiece()
		display.Flush()
	}
}
Exemplo n.º 24
0
func (vp *ViewPanel) Update(delta time.Duration) {
	// should set camera center
	p := vp.g.GetPlayer()
	if p != nil {
		vp.cam.SetCenter(image.Pt(p.GetPos()))
	} else {
		vp.cam.SetCenter(image.Pt(256/2, 256/2))
	}
}
Exemplo n.º 25
0
func TestIncludePointInDiff(t *testing.T) {
	rect := image.Rect(2, 2, 2, 2)

	IncludePointInDiff(&rect, image.Pt(5, 5))
	assert.Equal(t, rect, image.Rect(2, 2, 5, 5))

	IncludePointInDiff(&rect, image.Pt(0, 0))
	assert.Equal(t, rect, image.Rect(0, 0, 5, 5))
}
Exemplo n.º 26
0
func mright() {
	if !collide(image.Pt(pos.X+pcsz, pos.Y), piece) &&
		!collide(image.Pt(pos.X+pcsz, pos.Y+pcsz-DY), piece) {
		undrawpiece()
		pos.X += pcsz
		drawpiece()
		display.FlushImage()
	}
}
Exemplo n.º 27
0
func newWire() *wire {
	return &wire{
		index:         -1,
		pixels:        make([]image.Point, 0),
		bounds:        image.Rectangle{image.Pt(0, 0), image.Pt(0, 0)},
		transistors:   make([]*transistor, 0),
		isPowerSource: false,
	}
}
Exemplo n.º 28
0
// Test
func GetDefaultBackgroundAfterMask() (draw.Image, draw.Image, error) {

	src := LoadSrcImage("d:\\xxwn.png")
	mask := LoadMaskImage("d:\\mask.png")

	copy1, _ := GetWallImage(src, mask, image.Pt(80, 80))
	copy2, _ := GetPieceImage(src, mask, image.Pt(80, 80))
	return copy1, copy2, nil
}
Exemplo n.º 29
0
// x0, x1 are logical pixel
func (c *eanCoordinateConverter) translateBar(x0, x1 int, long bool) image.Rectangle {
	h := c.bound.Dy() - c.fontDim.Dy()
	if long {
		h += c.fontDim.Dy() / 2
	}
	return image.Rectangle{
		Min: c.bound.Min.Add(image.Pt(x0*c.scale, 0)),
		Max: c.bound.Min.Add(image.Pt(x1*c.scale, h)),
	}
}
Exemplo n.º 30
0
Arquivo: draw_test.go Projeto: oov/psd
func benchmarkDrawFallback(b *testing.B, path1 string, path2 string, d drawer, protectAlpha bool) {
	img, img2, err := loadNRGBAToNRGBAImages(path1, path2)
	if err != nil {
		b.Fatalf("%v", err)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		d.drawFallback(img, img2.Bounds(), img2, image.Pt(0, 0), nil, image.Pt(0, 0), protectAlpha)
	}
}