在不知道 x 和 y 的情况下裁剪图像 c#

Image cropping without knowing x and y c#

我在网上进行了一些搜索,但找不到解决我问题的方法。

我有各种 tiff 图像文件,它们都是白色背景并包含一个小图像

示例 tiff 图像大小为 2700 x 3500,小图像位于 200,200 且为 300x300

我需要裁剪掉这部分图像,现在这很容易,但我有很多 tiff 图像,tiff 中包含的小图像可能位于不同的位置并且大小不同。

我确实尝试遍历每个像素,找到第一个不是白色的像素实例,向下扫描到页面底部,然后继续扫描,这是一个非常繁重的过程,我得到的结果好坏参半,主要是因为我一直在寻找白色像素,有时 tiff 中包含的图像有白色部分。

我不确定如何解决这个问题,如有任何帮助,我们将不胜感激。

I did try going through every pixel, finding the first instance of a pixel that wasn't white, scanning down to the bottom of the page, then scanning along, its a very heavy process and I had mixed results, mostly because I was looking for white pixels and sometimes the image contained in the tiff had a white part.

你没有 post 你的代码,所以我不能确定你现在使用的是什么算法,但是遍历每个像素的一个循环足以找到白色背景上的图像。

示例代码:

int minX, minY, maxX, maxY;

minX = (int) image.Width;
minY = (int) image.Height;
maxX = maxY = 0;

for (int x = 0; x < image.Width; x++)
{
    for (int y = 0; y < image.Height; y++)
    {
        var color = GetPixelColor(image, x, y);
        if(color!=Colors.White)
        {
            minX = Math.Min(minX, x);
            maxX = Math.Max(maxX, x);
            minY = Math.Min(minY, y);
            maxY = Math.Max(maxY, y);
        }
    }
}

这里:

  • minX - 最上面的非白色像素的 X 坐标;
  • minY - 最左边的非白色像素的Y坐标;
  • maxX - 最下方非白色像素的 X 坐标;
  • maxY - 最右边的非白色像素的 Y 坐标。

所需图片从 (minX, minY)(maxX, maxY)

嵌套循环需要 Width * Height 个步骤才能完成。您需要实现 GetPixelColor 方法来按坐标检查像素。算法的性能主要取决于 GetPixelColor 的实现。如果您将像素颜色存储在数组中,则此算法对于大多数用途应该足够有效。