我有一张 2600x2600 的灰色图片。 或者可以看成一个unsigned short的矩阵。 我想找到最暗的(或通过计算逆向图片最亮的)正方形具有固定大小 N。N 可以参数化(如果有不止一个最暗的正方形,我想要所有)。
我读了detection-of-rectangular-bright-area-in-a-image-using-opencv 但它需要一个我没有的阈值,而且我搜索一个固定大小。
有没有人可以在 C++ 或 Python 中找到它?
最佳答案
For each row of the image,
Add up the N consecutive pixels, so you get W - N + 1 pixels.
For each column of the new image,
For each consecutive sequence of N pixels, (H - N + 1)
Add them up and compare to the current best.
要将每个连续的像素序列相加,您可以减去最后一个像素,然后添加下一个像素。
如果可以修改图像数组,您也可以将其重新用作存储。如果不是,内存优化将是只存储最新的列,并在第一个循环中的每个步骤中遍历它。
运行时间:O(w·h)
下面是一些 C# 代码,用于演示这一点(忽略像素格式和任何潜在的溢出):
List<Point> FindBrightestSquare(int[,] image, int N, out int squareSum)
{
int width = image.GetLength(0);
int height = image.GetLength(1);
if (width < N || height < N)
{
return false;
}
int currentSum;
for (int y = 0; y < height; y++)
{
currentSum = 0;
for (int x = 0; x < width; x++)
{
currentSum += image[x,y];
if (x => N)
{
currentSum -= image[x-N,y];
image[x-N,y] = currentSum;
}
}
}
int? bestSum = null;
List<Point> bestCandidates = new List<Point>();
for (int x = 0; x <= width-N; x++)
{
currentSum = 0;
for (int y = 0; y < height; y++)
{
currentSum += image[x,y];
if (y >= N)
{
currentSum -= image[x, y-N];
if (bestSum == null || currentSum > bestSum)
{
bestSum = currentSum;
bestCandidates.Clear();
bestCandidates.Add(new Point(x, y-N));
}
else if (currentSum == bestSum)
{
bestCandidates.Add(new Point(x, y-N));
}
}
}
}
squareSum = bestSum.Value;
return bestCandidates;
}
关于c++ - 从图片中检测最暗的固定大小的方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13303886/