116 lines
3.0 KiB
Java
116 lines
3.0 KiB
Java
package domain.image.processing.threshold;
|
|
|
|
import domain.image.GrayScaleMatrix;
|
|
import domain.image.Image;
|
|
|
|
public class Thresholding {
|
|
|
|
public static GrayScaleMatrix simpleThreshold(
|
|
Image image,
|
|
int threshold
|
|
) {
|
|
GrayScaleMatrix gray = image.toGrayScale();
|
|
|
|
int height = gray.getHeight();
|
|
int width = gray.getWidth();
|
|
|
|
double[][] data = gray.getRawData();
|
|
double[][] result = new double[height][width];
|
|
|
|
for (int y = 0; y < height; y++) {
|
|
for (int x = 0; x < width; x++) {
|
|
result[y][x] = data[y][x] >= threshold
|
|
? 255
|
|
: 0;
|
|
}
|
|
}
|
|
|
|
return new GrayScaleMatrix(result);
|
|
}
|
|
|
|
public static GrayScaleMatrix doubleThreshold(
|
|
Image image,
|
|
int threshold1,
|
|
int threshold2
|
|
) {
|
|
if (threshold1 > threshold2) {
|
|
int temp = threshold1;
|
|
threshold1 = threshold2;
|
|
threshold2 = temp;
|
|
}
|
|
|
|
GrayScaleMatrix gray = image.toGrayScale();
|
|
|
|
int height = gray.getHeight();
|
|
int width = gray.getWidth();
|
|
|
|
double[][] data = gray.getRawData();
|
|
double[][] result = new double[height][width];
|
|
|
|
for (int y = 0; y < height; y++) {
|
|
for (int x = 0; x < width; x++) {
|
|
|
|
double value = data[y][x];
|
|
|
|
if (value < threshold1) {
|
|
result[y][x] = 0;
|
|
} else if (value < threshold2) {
|
|
result[y][x] = 127;
|
|
} else {
|
|
result[y][x] = 255;
|
|
}
|
|
}
|
|
}
|
|
|
|
return new GrayScaleMatrix(result);
|
|
}
|
|
|
|
public static GrayScaleMatrix automaticThreshold(Image image) {
|
|
GrayScaleMatrix gray = image.toGrayScale();
|
|
|
|
double[][] data = gray.getRawData();
|
|
|
|
double threshold = (gray.getMinValue() + gray.getMaxValue()) / 2.0;
|
|
|
|
while (true) {
|
|
double lowerSum = 0;
|
|
double upperSum = 0;
|
|
|
|
int lowerCount = 0;
|
|
int upperCount = 0;
|
|
|
|
for (int y = 0; y < gray.getHeight(); y++) {
|
|
for (int x = 0; x < gray.getWidth(); x++) {
|
|
|
|
double value = data[y][x];
|
|
|
|
if (value <= threshold) {
|
|
lowerSum += value;
|
|
lowerCount++;
|
|
} else {
|
|
upperSum += value;
|
|
upperCount++;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (lowerCount == 0 || upperCount == 0) {
|
|
break;
|
|
}
|
|
|
|
double lowerMean = lowerSum / lowerCount;
|
|
double upperMean = upperSum / upperCount;
|
|
|
|
double newThreshold = (lowerMean + upperMean) / 2.0;
|
|
|
|
if (Math.abs(newThreshold - threshold) < 0.5) {
|
|
threshold = newThreshold;
|
|
break;
|
|
}
|
|
|
|
threshold = newThreshold;
|
|
}
|
|
|
|
return simpleThreshold(image, (int) threshold);
|
|
}
|
|
} |