Created
February 1, 2021 01:46
-
-
Save dmbfm/484726b6c47b99537fb12ae09629f941 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"image" | |
"image/color" | |
"image/draw" | |
"image/png" | |
"math" | |
"math/rand" | |
"os" | |
) | |
func TresholdRandom(img image.Image, t float32, randomRange float32) (image.Image, image.Image, float64) { | |
result := image.NewGray(img.Bounds()) | |
qerr := image.NewGray(img.Bounds()) | |
var averr float64 | |
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ { | |
for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ { | |
r, g, b, _ := img.At(x, y).RGBA() | |
v := float32(math.Pow(float64(uint8((r + g + b) / 3)) / 255.0, 2.2)) | |
randomFactor := randomRange * (rand.Float32() - 0.5) | |
newV := v + randomFactor | |
var final uint8 | |
if newV > t { | |
final = 255 | |
} else { | |
final = 0 | |
} | |
result.Set(x, y, color.Gray{ final }) | |
delta := math.Abs(float64(final) - float64(255.0 * v)) | |
qerr.Set(x, y, color.Gray{ uint8(delta) }) | |
averr += delta / float64((img.Bounds().Max.X * img.Bounds().Max.Y)) | |
} | |
} | |
return result, qerr, averr/255 | |
} | |
func ThresholdRandomGallery(img image.Image) image.Image { | |
rect := img.Bounds() | |
gallery := image.NewGray(image.Rect(0, 0, 11 * rect.Dx(), 11 * rect.Dy())) | |
var t float32 = 0.0 | |
var r float32 = 0.0 | |
width := rect.Dx() | |
height := rect.Dy() | |
x := 0 | |
y := 0 | |
for i := 0; i < 11; i++ { | |
for j := 0; j < 11; j++ { | |
subImage, _, _ := TresholdRandom(img, t, r) | |
rectangle := image.Rect(x, y, x + width, y + height) | |
fmt.Println(rectangle, t, r) | |
draw.Draw(gallery, rectangle, subImage, image.ZP, draw.Over) | |
r += 0.1 | |
x += width | |
} | |
r = 0 | |
x = 0 | |
t += 0.1 | |
y += height | |
} | |
return gallery | |
} | |
func main() { | |
r, err := os.Open("image.png") | |
if err != nil { | |
panic(err) | |
} | |
img, err := png.Decode(r) | |
if err != nil { | |
panic(err) | |
} | |
//out, qerr, averr := TresholdRandom(img, 0.48, 0.35) | |
out := ThresholdRandomGallery(img) | |
w, err := os.Create("out.png") | |
if err != nil { | |
panic(err) | |
} | |
//w2, err := os.Create("qerr.png") | |
//if err != nil { | |
// panic(err) | |
//} | |
err = png.Encode(w, out) | |
//err = png.Encode(w2, qerr) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment