我有一個QImage,我需要修剪周圍的白色(即裁剪它只有非白色區域)。是否有函數來獲取QImage的非白色區域的邊界框?
QImage或QPixmap是否具有內置函數,將返回圖像非白色區域的邊界框,類似於QGraphicsPixmapItem::opaqueArea()
?意思是,在該邊界框之外不存在非白色像素。
我有一個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);
}
聲明:此代碼大概可以優化。我沒有測試過它,它看起來像編譯,但可能有錯別字。我只是把它放在那裏來展示大致的想法。