检查图像像素强度的方法

Method For Checking Image Pixel Intensities

本文关键字:方法 图像 像素 检查      更新时间:2023-10-16

我有一个基于OCR的iPhone应用程序,它可以接收灰度图像并将其设置为黑白阈值以查找文本(使用opencv)。这适用于白底黑字的图像。当图像是黑色背景上的白色文本时,我遇到了自动切换到反向阈值的问题。是否有一种广泛使用的算法来检查图像,以确定它是暗背景上的浅色文本,反之亦然?有人能推荐一种干净的工作方法吗?请记住,我只处理iPhone相机的灰度图像。

非常感谢。

由于我现在处理的是灰度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
}

我会检查每个像素,检查它是亮是暗。如果暗像素数大于亮像素数,则必须反转图片。

查看此处了解如何确定亮度:检测图像iOS 中的黑色像素

这就是如何绘制UIImage反转:

[imyImage drawInRect:theImageRect blendMode:kCGBlendModeDifference alpha:1.0];