算法
统计一条线上黑色点数量,少于线长10%(阈值,也可设置成变量调整)判定为边界,执行裁剪。
cpp
void ImageWidget::deleteBlackBorder(BorderType border_type)
{
switch (border_type) {
case BORDER_LEFT:{
int x1 = 0;
for (int x=0; x<image.width()/4; x++) {
int c = 0;
for (int y=0; y<image.height(); y++) {
QRgb rgb = image.pixel(x,y);
int r = qRed(rgb);
int g = qGreen(rgb);
int b = qBlue(rgb);
if (r<10 && g<10 && b<10) {
c++;
}
}
float p = c;
//qDebug() << x << ":" << c << image.height() << p / image.height();
p = p / image.height();
if (p < 0.1) {
x1 = x;
emit statusBar2Message("DeleteBlackBorder(x=" + QString::number(x) + ")");
break;
}
}
image = image.copy(x1, 0, image.width() - x1, image.height());
imgtemp = image;
update();
break;}
case BORDER_RIGHT:{
int x1 = image.width() - 1;
for (int x=x1; x>image.width()*3/4; x--) {
int c = 0;
for (int y=0; y<image.height(); y++) {
QRgb rgb = image.pixel(x,y);
int r = qRed(rgb);
int g = qGreen(rgb);
int b = qBlue(rgb);
if (r<10 && g<10 && b<10) {
c++;
}
}
float p = c;
//qDebug() << x << ":" << c << image.height() << p / image.height();
p = p / image.height();
if (p < 0.1) {
x1 = x;
emit statusBar2Message("DeleteBlackBorder(x=" + QString::number(x) + ")");
break;
}
}
image = image.copy(0, 0, x1, image.height());
imgtemp = image;
update();}
break;
case BORDER_TOP:{
int y1 = 0;
for (int y=0; y<image.height()/4; y++) {
int c = 0;
for (int x=0; x<image.width(); x++) {
QRgb rgb = image.pixel(x,y);
int r = qRed(rgb);
int g = qGreen(rgb);
int b = qBlue(rgb);
if (r<10 && g<10 && b<10) {
c++;
}
}
float p = c;
//qDebug() << y << ":" << c << image.width() << p / image.width();
p = p / image.width();
if (p < 0.1) {
y1 = y;
emit statusBar2Message("DeleteBlackBorder(y=" + QString::number(y) + ")");
break;
}
}
image = image.copy(0, y1, image.width()-1, image.height() - y1);
imgtemp = image;
update();
break;}
case BORDER_BOTTOM:{
int y1 = image.height() - 1;
for (int y=y1; y>image.height()*3/4; y--) {
int c = 0;
for (int x=0; x<image.width(); x++) {
QRgb rgb = image.pixel(x,y);
int r = qRed(rgb);
int g = qGreen(rgb);
int b = qBlue(rgb);
if (r<10 && g<10 && b<10) {
c++;
}
}
float p = c;
//qDebug() << y << ":" << c << image.height() << p / image.height();
p = p / image.height();
if (p < 0.1) {
y1 = y;
emit statusBar2Message("DeleteBlackBorder(y=" + QString::number(y) + ")");
break;
}
}
image = image.copy(0, 0, image.width() -1, y1);
imgtemp = image;
update();}
break;
}
}
https://www.bilibili.com/video/BV1GSEj6UELh/
Qt 版做好了,可以移植到 Android 和 JS。