Поскольку я имею дело с полутоновым масштабом IplImage
, в этот момент я не мог подсчитать черные или белые пиксели, но мне пришлось подсчитать количество пикселей выше заданного порога "яркости". Я просто использовал пиксели границы, так как это дешевле и по-прежнему дает мне достаточно информации, чтобы принять правильное решение.
IplImage *image;
int sum = 0; // Number of light pixels
int threshold = 135; // Light/Dark intensity threshold
/* Count number of light pixels at border of image. Must convert to unsigned char type to make range 0-255. */
// Check every other pixel of top and bottom
for (int i=0; i<(image->width); i+=2) {
if ((unsigned char)image->imageData[i] >= threshold) { // Check top
sum++;
}
if ((unsigned char)image->imageData[(image->width)*(image->height)
- image->width + i] >= threshold) { // Check bottom
sum++;
}
}
//Check every other pixel of left and right Sides
for (int i=0; i<(image->height); i+=2) {
if ((unsigned char)image->imageData[i*(image->width)] >= threshold) { // Check left
sum++;
}
if ((unsigned char)image->imageData[i*(image->width) + (image->width) - 1] >= threshold) { // Check right
sum++;
}
}
// If more than half of the border pixels are light, use inverse threshold to find dark characters
if (sum > ((image->width/2) + (image->height/2))) {
// Use inverse binary threshold because background is light
}
else {
// Use standard binary threshold because background is dark
}