是否有一个函数来获得一个QImage的非白色区域的边界框
Is there a function to get the bounding box of the non-white area of a QImage?
我有一个QImage,我需要修剪周围的白色(即裁剪到非白色区域)。
QImage或QPixmap是否有一个内置函数,将返回图像的非白色区域的边界框,类似于QGraphicsPixmapItem::opaqueArea()
?也就是说,没有非白色像素在边界框之外。
我没有看到一个内置的函数,但它应该很容易让你自己的,像这样:
QRect getBoundsWithoutColor(QImage qImage, const Qcolor &exclusionColor = Qt:white)
{
QRect ofTheKing;
int maxX = 0; int minX = qImage.width;
int maxY = 0; int minY = qImage.height;
for(int x=0; x < qImage.width(); x++)
for(int y=0; y < qImage.height(); y++)
if (QColor.fromRgb(qImage.pixel(x, y)) != exclusionColor)
{
if(x < minX) minX = x;
if(x > maxX) maxX = x;
if(y < minY) minY = y;
if(y > maxY) maxY = y;
}
if (minX > maxX || minY > maxY)
// The whole picture is white. How you wanna handle this case is up to you.
else
ofTheKing.setCoords(minX, minY, maxX+1, maxY+1);
return ofTheKing;
}
QImage中没有内置这样的函数,但是由于QImage允许直接访问像素数据,所以自己编写代码应该不会太难。在我的脑海中,它可能看起来像这样。
const QRgb CROP_COLOR = QColor(Qt::white).rgb();
QImage crop(const QImage& image)
{
QRect croppedRegion(0, 0, image.width(), image.height());
// Top
for (int row = 0; row < image.height(); row++) {
for (int col = 0; col < image.width(); col++) {
if (image.pixel(col, row) != CROP_COLOR) {
croppedRegion.setTop(row);
row = image.height();
break;
}
}
}
// Bottom
for (int row = image.height() - 1; row >= 0; row--) {
for (int col = 0; col < image.width(); col++) {
if (image.pixel(col, row) != CROP_COLOR) {
croppedRegion.setBottom(row);
row = -1;
break;
}
}
}
// Left
for (int col = 0; col < image.width(); col++) {
for (int row = 0; row < image.height(); row++) {
if (image.pixel(col, row) != CROP_COLOR) {
croppedRegion.setLeft(col);
col = image.width();
break;
}
}
}
// Right
for (int col = image.width(); col >= 0; col--) {
for (int row = 0; row < image.height(); row++) {
if (image.pixel(col, row) != CROP_COLOR) {
croppedRegion.setRight(col);
col = -1;
break;
}
}
}
return image.copy(croppedRegion);
}
免责声明:此代码可能可以优化。我还没有测试它,它看起来可以编译,但可能有一个错别字。我把它放在这里只是为了说明大意
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '