This plugin calculates the "optimal" thresholding value for converting a
graymap to a pixelmap
(i.e grey to b/w).
I think it works, but I do not manage to write pixels to the drawable.
Could someone give a hint on how to accomplish this?
#!/usr/bin/env python
import struct
import math
import gimp
from gimpfu import *
def python_otsu_threshold(img, drawable):
width = drawable.width
height = drawable.height
bpp = drawable.bpp
pr = drawable.get_pixel_rgn(0, 0, width, height, True, False)
gimp.progress_init("Thresholding...")
maxval = 255
hist = []
for i in range(0,maxval+1):
hist.append(0)
for y in range(0,height):
row = pr[0:width, y]
for x in range(0, width):
pixel = ord(row[x])
hist[pixel] += 1
gimp.progress_update(y / float(height))
chist = []
chist.append(hist[0])
cmom = []
cmom.append(0 * hist[0])
hist_max = hist[0]
for i in range(1,maxval+1):
chist.append ( chist[i-1] + hist[i] )
cmom.append ( cmom[i-1] + ( i * hist[i] ) )
if (hist[i] > hist_max):
hist_max = hist[i]
chist_max = chist[maxval]
cmom_max = float(cmom[maxval])
bvar_max = 0
threshold = 0
re_size = width * height
bvars = []
for i in range(0,maxval):
if ( (chist[i] > 0) and (chist[i] < re_size) ):
bvar = float(cmom[i]) / chist[i];
bvar -= ( cmom_max - cmom[i]) / ( re_size - chist[i]);
bvar *= bvar; bvar *= chist[i]; bvar *= ( re_size - chist[i] );
bvars.append(bvar)
if (bvar > bvar_max):
bvar_max = bvar
threshold = i
else:
bvars.append(bvar_max)
for y in range(0,height):
row = pr[0:width, y]
for x in range(0, width):
pixel = ord(row[x])
if pixel < threshold:
row[x] = chr(0)
else:
row[x] = chr(255)
drawable.merge_shadow()
register(
"python_fu_threshold",
"Optimal Binary Threshold on region using Otsu's method",
"Optimal Binary Threshold on region using Otsu's method (adapted
from code in GOCR-0.14)",
"Lode Leroy",
"Lode Leroy",
"2006",
"/Filters/Misc/_Threshold...",
"*",
[],
[],
python_otsu_threshold)
main()