gpt4 book ai didi

c# - 从图像中删除周围的空白

转载 作者:IT王子 更新时间:2023-10-29 04:20:02 43 4
gpt4 key购买 nike

我有一组从客户那里收到的产品图片。每张产品图片都是某物的图片,并且是在白色背景下拍摄的。我想裁剪图像的所有周围部分,但只留下中间的产品。这可能吗?

例如:[ http://www.5dnet.de/media/catalog/product/d/r/dress_shoes_5.jpg][1]

我不想删除所有白色像素,但我确实希望裁剪图像,使最上面的像素行包含一个非白色像素,最左侧的垂直像素行包含一个非白色像素,最底部的水平像素行包含一个非白色像素等。

C# 或 VB.net 代码将不胜感激。

最佳答案

我发现我必须调整 Dmitri 的答案以确保它适用于实际上不需要裁剪(水平、垂直或两者)的图像...

    public static Bitmap Crop(Bitmap bmp)
{
int w = bmp.Width;
int h = bmp.Height;

Func<int, bool> allWhiteRow = row =>
{
for (int i = 0; i < w; ++i)
if (bmp.GetPixel(i, row).R != 255)
return false;
return true;
};

Func<int, bool> allWhiteColumn = col =>
{
for (int i = 0; i < h; ++i)
if (bmp.GetPixel(col, i).R != 255)
return false;
return true;
};

int topmost = 0;
for (int row = 0; row < h; ++row)
{
if (allWhiteRow(row))
topmost = row;
else break;
}

int bottommost = 0;
for (int row = h - 1; row >= 0; --row)
{
if (allWhiteRow(row))
bottommost = row;
else break;
}

int leftmost = 0, rightmost = 0;
for (int col = 0; col < w; ++col)
{
if (allWhiteColumn(col))
leftmost = col;
else
break;
}

for (int col = w - 1; col >= 0; --col)
{
if (allWhiteColumn(col))
rightmost = col;
else
break;
}

if (rightmost == 0) rightmost = w; // As reached left
if (bottommost == 0) bottommost = h; // As reached top.

int croppedWidth = rightmost - leftmost;
int croppedHeight = bottommost - topmost;

if (croppedWidth == 0) // No border on left or right
{
leftmost = 0;
croppedWidth = w;
}

if (croppedHeight == 0) // No border on top or bottom
{
topmost = 0;
croppedHeight = h;
}

try
{
var target = new Bitmap(croppedWidth, croppedHeight);
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(bmp,
new RectangleF(0, 0, croppedWidth, croppedHeight),
new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),
GraphicsUnit.Pixel);
}
return target;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Values are topmost={0} btm={1} left={2} right={3} croppedWidth={4} croppedHeight={5}", topmost, bottommost, leftmost, rightmost, croppedWidth, croppedHeight),
ex);
}
}

关于c# - 从图像中删除周围的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/248141/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com