int ProcParty::countCheckLetters(const QImage & imgCheck) { //очерняем const int width = imgCheck.width(); const int height = imgCheck.height(); BoolMatrix checkMatrix(imgCheck); for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { QRgb rgb = imgCheck.pixel(x, y); QColor cl(rgb); if (cl.hue() >= 13 && cl.hue() <= 33) { checkMatrix.set(x, y, false); //imgCheck.setPixel(x, y, qRgb(0, 0, 0)); } else { checkMatrix.set(x, y, true); //imgCheck.setPixel(x, y, qRgb(255, 255, 255)); } } } //сканируем рисунок на предмет пробелов int countLetters = 0; int count = 0; bool isBlackLinePrev = true; bool isBlackLineCurr = true; bool isLetterFinish = false; QPoint ptLeft, ptRight; for (int w = 0; w < width; ++w) { isLetterFinish = false; isBlackLineCurr = true; for (int h = 0; h < height; ++h) { if (checkMatrix.at(w, h) == true) { isBlackLineCurr = false; break; } } if ((isBlackLinePrev == true) && (isBlackLineCurr == false)) { countLetters++; isBlackLinePrev = false; } else if ((isBlackLinePrev == false) && (isBlackLineCurr == true)) { isBlackLinePrev = true; isLetterFinish = true; } if (isLetterFinish) { count++; } } return count; }
QStandardItem* QgsLegendModel::itemFromSymbol( QgsSymbol* s, int opacity, const QString& layerID ) { QgsComposerSymbolItem* currentSymbolItem = 0; //label QString itemText; QString label; QString lowerValue = s->lowerValue(); QString upperValue = s->upperValue(); label = s->label(); //Take the label as item text if it is there if ( !label.isEmpty() ) { itemText = label; } //take single value else if ( lowerValue == upperValue || upperValue.isEmpty() ) { itemText = lowerValue; } else //or value range { itemText = lowerValue + " - " + upperValue; } //icon item QImage symbolImage; switch ( s->type() ) { case QGis::Point: symbolImage = s->getPointSymbolAsImage(); break; case QGis::Line: symbolImage = s->getLineSymbolAsImage(); break; case QGis::Polygon: symbolImage = s->getPolygonSymbolAsImage(); break; default: return 0; } if ( opacity != 255 ) { //todo: manipulate image pixel by pixel... QRgb oldColor; for ( int i = 0; i < symbolImage.height(); ++i ) { QRgb* scanLineBuffer = ( QRgb* ) symbolImage.scanLine( i ); for ( int j = 0; j < symbolImage.width(); ++j ) { oldColor = symbolImage.pixel( j, i ); scanLineBuffer[j] = qRgba( qRed( oldColor ), qGreen( oldColor ), qBlue( oldColor ), opacity ); } } } currentSymbolItem = new QgsComposerSymbolItem( itemText ); if ( mHasTopLevelWindow )//only use QIcon / QPixmap if we have a running x-server { currentSymbolItem->setIcon( QIcon( QPixmap::fromImage( symbolImage ) ) ); } if ( !currentSymbolItem ) { return 0; } //Pass deep copy of QgsSymbol as user data. Cast to void* necessary such that QMetaType handles it QgsSymbol* symbolCopy = new QgsSymbol( *s ); currentSymbolItem->setSymbol( symbolCopy ); currentSymbolItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable ); currentSymbolItem ->setLayerID( layerID ); return currentSymbolItem; }
int main( int*, char**) { QImage *img; img = new QImage( "in.png" ); int w,h; int y; img->setAlphaBuffer( TRUE ); *img = img->convertDepth( 32 ); w = img->width(); h = img->height(); #if 0 for ( y = 0; y < h; y ++ ) { uint *line = (uint*)img->scanLine( y ); for ( int x = 0; x < w; x++ ) { uint pixel = line[x]; int r = qRed(pixel); int g = qGreen(pixel); int b = qBlue(pixel); int min = QMIN( r, QMIN( g, b ) ); int max = QMAX( r, QMAX( g, b ) ); r -= min; g -= min; b -= min; if ( max !=min ) { r = (r*255)/(max-min); g = (g*255)/(max-min); b = (b*255)/(max-min); } int a = 255-min; a -= (max-min)/3; //hack more transparency for colors. line[x] = qRgba( r, g, b, a ); } } #endif *img = img->smoothScale( w/2, h/2 ); qDebug( "saving out.png"); img->save( "out.png", "PNG" ); w = img->width(); h = img->height(); QImage *img2 = new QImage( w, h, 32 ); img2->setAlphaBuffer( TRUE ); for ( y = 0; y < h; y++ ) { for ( int x = 0; x < w; x++ ) { QRgb shader = img->pixel( x, y ); int as = qAlpha(shader)/3; int r = (qRed(shader)*(255-as))/255; int g = (qGreen(shader)*(255-as))/255; int b = (qBlue(shader)*(255-as))/255; img2->setPixel( x, y, qRgba(r,g,b,as) ); } } img2->save( "outshade.png", "PNG" ); }
// Computes SSIM - see https://en.wikipedia.org/wiki/Structural_similarity // The value is computed for the luminance component and the average value is returned void ImageComparer::compareImages(const QImage& resultImage, const QImage& expectedImage) { const int L = 255; // (2^number of bits per pixel) - 1 const double K1 { 0.01 }; const double K2 { 0.03 }; const double c1 = pow((K1 * L), 2); const double c2 = pow((K2 * L), 2); // First go over all full 8x8 blocks // This is done in 3 loops // 1) Read the pixels into a linear array (an optimization) // 2) Calculate mean // 3) Calculate variance and covariance // // p - pixel in expected image // q - pixel in result image // const int WIN_SIZE = 8; int x{ 0 }; // column index (start of block) int y{ 0 }; // row index (start of block // Pixels are processed in square blocks double p[WIN_SIZE * WIN_SIZE]; double q[WIN_SIZE * WIN_SIZE]; _ssimResults.results.clear(); int windowCounter{ 0 }; double ssim{ 0.0 }; double worstTileValue{ 1.0 }; double min { 1.0 }; double max { -1.0 }; while (x < expectedImage.width()) { int lastX = x + WIN_SIZE - 1; if (lastX > expectedImage.width() - 1) { x -= (lastX - expectedImage.width()); } while (y < expectedImage.height()) { int lastY = y + WIN_SIZE - 1; if (lastY > expectedImage.height() - 1) { y -= (lastY - expectedImage.height()); } // Collect pixels into linear arrays int i{ 0 }; for (int xx = 0; xx < WIN_SIZE && x + xx < expectedImage.width(); ++xx) { for (int yy = 0; yy < WIN_SIZE && y + yy < expectedImage.height(); ++yy) { // Get pixels QRgb pixelP = expectedImage.pixel(QPoint(x + xx, y + yy)); QRgb pixelQ = resultImage.pixel(QPoint(x + xx, y + yy)); // Convert to luminance p[i] = R_Y * qRed(pixelP) + G_Y * qGreen(pixelP) + B_Y * qBlue(pixelP); q[i] = R_Y * qRed(pixelQ) + G_Y * qGreen(pixelQ) + B_Y * qBlue(pixelQ); ++i; } } // Calculate mean double mP{ 0.0 }; // average value of expected pixel double mQ{ 0.0 }; // average value of result pixel for (int j = 0; j < WIN_SIZE * WIN_SIZE; ++j) { mP += p[j]; mQ += q[j]; } mP /= (WIN_SIZE * WIN_SIZE); mQ /= (WIN_SIZE * WIN_SIZE); // Calculate variance and covariance double sigsqP{ 0.0 }; double sigsqQ{ 0.0 }; double sigPQ{ 0.0 }; for (int j = 0; j < WIN_SIZE * WIN_SIZE; ++j) { sigsqP += pow((p[j] - mP), 2); sigsqQ += pow((q[j] - mQ), 2); sigPQ += (p[j] - mP) * (q[j] - mQ); } sigsqP /= (WIN_SIZE * WIN_SIZE); sigsqQ /= (WIN_SIZE * WIN_SIZE); sigPQ /= (WIN_SIZE * WIN_SIZE); double numerator = (2.0 * mP * mQ + c1) * (2.0 * sigPQ + c2); double denominator = (mP * mP + mQ * mQ + c1) * (sigsqP + sigsqQ + c2); double value { numerator / denominator }; _ssimResults.results.push_back(value); ssim += value; if (value < min) min = value; if (value > max) max = value; if (value < worstTileValue) { worstTileValue = value; } ++windowCounter; y += WIN_SIZE; } x += WIN_SIZE; y = 0; } _ssimResults.width = (int)(expectedImage.width() / WIN_SIZE); _ssimResults.height = (int)(expectedImage.height() / WIN_SIZE); _ssimResults.min = min; _ssimResults.max = max; _ssimResults.ssim = ssim / windowCounter; _ssimResults.worstTileValue = worstTileValue; };
table LaserEnv::read(const QImage& img) { table ret(n, vector<cc>(n)); const double Pi = acos(0.0)*2; vector< vector<bool> > used(n, vector<bool>(n)); const int di[] = {-1, 0, 1, 0}; const int dj[] = {0, 1, 0, -1}; queue<int> q; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { QRgb rgb = img.pixel(j, i); bool black = !qRed(rgb) && !qGreen(rgb) && !qBlue(rgb); if (black || used[i][j]) continue; vector<int> connected; q.push(i); q.push(j); connected.push_back(i); connected.push_back(j); used[i][j] = true; int mini = 1e9, maxi = -1e9; int minj = 1e9, maxj = -1e9; while (!q.empty()) { int vi = q.front(); q.pop(); int vj = q.front(); q.pop(); for (int k = 0; k < 4; k++) { int ni = vi+di[k]; int nj = vj+dj[k]; if (ni >= 0 && ni < n && nj >= 0 && nj < n && !used[ni][nj]) { QRgb rgb2 = img.pixel(nj, ni); bool black2 = !qRed(rgb2) && !qGreen(rgb2) && !qBlue(rgb2); if (black2) continue; used[ni][nj] = true; q.push(ni); q.push(nj); connected.push_back(ni); connected.push_back(nj); mini = min(mini, ni); maxi = max(maxi, ni); minj = min(minj, nj); maxj = max(maxj, nj); } } } double r = (1+rand())*1./(RAND_MAX+1.); //double phi = (1+rand())*1./(RAND_MAX+1.); //double standardNormalDist = cos(2*Pi*phi) * sqrt(-2*log(r)); //double normalVal = deviation * standardNormalDist; double cx = 0.5*(mini+maxi); double cy = 0.5*(minj+maxj); double cr = max(maxi-mini, maxj-minj)+1; for (int k = 0; k < (int)connected.size(); k+=2) { // Point inside the circle int vi = connected[k]; int vj = connected[k+1]; double distToCenterOfCircle = (pt(cx, cy)-pt(vi, vj)).len(); double ry = cy + distToCenterOfCircle; //cerr << "cx = " << cx << endl; //cerr << "cy = " << cy << endl; //cerr << "cr = " << cr << endl; double phiVal = calculateRayPhi(cx, cy, cr, ry); //cerr << "phiVal = " << phiVal << endl; //cerr << "normalVal = " << normalVal << endl; ret[vi][vj] = cc(1, phiVal); } } return ret; }
void ImageProcessor::recognizePiece(RectArea rect, QImage& img, PieceSquare &ChessDeskPiece) { std::vector<std::vector<kaverage> > vsquare (rect.width,std::vector<kaverage>( rect.height)); int average; int NumOfPixels=0; int HasPiece=0; for(int i=1;i<rect.width-1;i++) { for(int j=1; j<rect.height-1;j++) { vsquare[i][j].Gray=qGray(img.pixel(i+rect.x,j+rect.y)); if (vsquare[i][j].Gray) NumOfPixels++; if (vsquare[i][j].Gray && !HasPiece) HasPiece=1; vsquare[i][j].k=0; average+=vsquare[i][j].Gray; } } average=average/(rect.width*rect.height); if (HasPiece) { double Elongation=0; double Compaction=0; int Perimeter=0; int VolumeArea=0; for(int i=1;i<rect.width-1;i++) { for(int j=1; j<rect.height-1;j++) { if (vsquare[i][j].Gray) { VolumeArea++; if (!vsquare[i+1][j+1].Gray || !vsquare[i+1][j].Gray || !vsquare[i+1][j-1].Gray || !vsquare[i][j+1].Gray || !vsquare[i][j-1].Gray || !vsquare[i-1][j+1].Gray || !vsquare[i-1][j].Gray || !vsquare[i-1][j-1].Gray) { Perimeter++; } } } } Compaction=static_cast<double>(Perimeter*Perimeter)/VolumeArea; //writeLog(QString("Perimeter %1 \n Square %2").arg(Perimeter).arg(VolumeArea)); writeLog(QString("Compact %3").arg(Compaction)); int XCenterMass=0; int YCenterMass=0; for(int i=1;i<rect.width-1;i++) { for(int j=1; j<rect.height-1;j++) { if (vsquare[i][j].Gray) { XCenterMass+=i; YCenterMass+=j; } } } XCenterMass/=NumOfPixels; YCenterMass/=NumOfPixels; //writeLog(QString("XCenterMass %1 YCenterMass %2").arg(XCenterMass).arg(YCenterMass)); double m02=0; double m20=0; double m11=0; for(int i=1;i<rect.width-1;i++) { for(int j=1; j<rect.height-1;j++) { if (vsquare[i][j].Gray) { m02+=(YCenterMass-j)*(YCenterMass -j); m20+=(XCenterMass-i)*(XCenterMass -i); m11+=(i-XCenterMass)*(j-YCenterMass); } } } Elongation=(m20+m02+sqrt((m20-m02)*(m20-m02)+4*m11*m11))/ (m20+m02-sqrt((m20-m02)*(m20-m02)+4*m11*m11)); writeLog(QString("Elongation %1 \n").arg(Elongation)); if (Elongation>2) { ChessDeskPiece.Type=3; // Pawn } else { if (Compaction>50) { ChessDeskPiece.Type=2; //Queen } else { ChessDeskPiece.Type=1; //King } } } else { ChessDeskPiece.Type=0; } if (DebugMode) { sendImage(*image); writeLog(QString(tr("Piece recognition"))); } }
void ImageOperations::featureScale( const OpGrayImage& img, OpGrayImage& imgRet ) { QImage qimg = img.getQtImage(); QImage qimgRet; qimgRet.create(qimg.width()/2, qimg.height()/2, 32); for( int y=0; y<qimg.height(); y+=2 ) { for( int x=0; x<qimg.width(); x+=2 ) { if( (int(x/2) < qimgRet.width()) && (int(y/2) < qimgRet.height())) { if( (qRed (qimg.pixel(x,y)) == 0) && // If pixel in (qGreen(qimg.pixel(x,y)) == 0) && // image contains feature (qBlue (qimg.pixel(x,y)) == 0)) { // set in scaled qimgRet.setPixel(int(x/2), int(y/2), qRgb(0,0,0)); } else { if ((x < qimg.width()-1) && // Else, if pixel ((qRed (qimg.pixel(x+1,y)) == 0) && // to the right (qGreen(qimg.pixel(x+1,y)) == 0) && // contains feature (qBlue (qimg.pixel(x+1,y)) == 0))) { // set in scaled. qimgRet.setPixel(int(x/2), int(y/2), qRgb(0,0,0)); } else { if( (y < qimg.height()-1) && // Else if pixel ((qRed (qimg.pixel(x,y+1)) == 0) && // below contains (qGreen(qimg.pixel(x,y+1)) == 0) && // feature, set (qBlue (qimg.pixel(x,y+1)) == 0))) { // in scaled. qimgRet.setPixel(int(x/2), int(y/2), qRgb(0,0,0)); } else { // Else if pixel if( ((x < qimg.width()-1) && // to the right (y < qimg.height()-1)) && // and below ((qRed (qimg.pixel(x,y+1)) == 0) && // contains (qGreen(qimg.pixel(x,y+1)) == 0) && // feature, set (qBlue (qimg.pixel(x,y+1)) == 0))) { // it in scaled. qimgRet.setPixel(int(x/2), int(y/2), qRgb(0,0,0)); } else { // Else set qimgRet.setPixel(int(x/2), int(y/2), // non-feature in qRgb(255,255,255)); // scaled. } } } } } } } OpGrayImage tmp(qimgRet); imgRet = tmp; }
void processar::aplicar(QImage tempImg, int brilho, bool isImage){ if(isImage) { QColor tempColor; QRgb cor; //int r, g, b; int cinza; //if (tempImg.isGrayscale()){ for(int i = 0; i < tempImg.width(); i++){ for(int j = 0; j < tempImg.height(); j++){ tempColor = tempImg.pixel(i,j); cinza = 255 - (brilho + tempColor.black()); if (cinza > 255) cinza = 255; else if(cinza < 0) cinza = 0; cor = qRgb(cinza, cinza, cinza); tempImg.setPixel(i, j, cor); } //Final For Altura } //Final For Largura imgFinal -> setPixmap(QPixmap::fromImage(tempImg)); imgFinal -> adjustSize(); imgFinalCopy = tempImg.copy(); processado = true; //} //Final do If greyScale /*for(int i = 0; i < tempImg.width(); i++){ for(int j = 0; j < tempImg.height(); j++){ tempColor = tempImg.pixel(i,j); r = brilho + tempColor.red(); g = brilho + tempColor.green(); b = brilho + tempColor.blue(); if (r > 255) r = 255; else if (r < 0) r = 0; if (g > 255) g = 255; else if (g < 0) g = 0; if (b > 255) b = 255; else if (b < 0) b = 0; cor = qRgb(r, g, b); tempImg.setPixel(i, j, cor); } imgFinal -> setPixmap(QPixmap::fromImage(tempImg)); imgFinal -> adjustSize(); imgFinalCopy = tempImg.copy(); processado = true; } */ } }
void ItemScene::determinePointsInSelection() { QRectF controlRect = this->selectionPathItem->path().controlPointRect(); QPainterPath path = this->selectionPathItem->path(); QImage sourceImage = this->imageFileItem->pixmap().toImage(); QImage extractedImage(controlRect.width(), controlRect.height(), QImage::Format_RGB888); for(int yPos = controlRect.topLeft().y(); yPos < controlRect.topLeft().y() + controlRect.height(); yPos++) { for(int xPos = controlRect.topLeft().x(); xPos < controlRect.topLeft().x() + controlRect.width(); xPos++) { if(path.contains(QPointF(xPos, yPos))) { extractedImage.setPixel( xPos - (controlRect.topRight().x() - controlRect.width()), yPos - (controlRect.bottomLeft().y() - controlRect.height()),sourceImage.pixel(xPos, yPos)); } else extractedImage.setPixel( xPos - (controlRect.topRight().x() - controlRect.width()), yPos - (controlRect.bottomLeft().y() - controlRect.height()), QRgb(qRgb(255,255,255))); } } this->imageFileItem->setPixmap(QPixmap::fromImage(extractedImage)); this->imageFileItem->setPos(this->sceneRect().center().operator -=(QPointF(extractedImage.width()/2, extractedImage.height()/2))); this->imageFileItem->update(); this->removeItem(this->selectionPathItem); for(QList<SelectionMarker*>::iterator iterator = this->selectionMarkers->begin(); iterator != this->selectionMarkers->end(); iterator++) { this->removeItem( (*iterator)); } }
void tst_QWindowSurface::grabWidget() { QWidget parentWidget; QWidget childWidget(&parentWidget); QWidget babyWidget(&childWidget); parentWidget.resize(300, 300); childWidget.setGeometry(50, 50, 200, 200); childWidget.setAutoFillBackground(true); babyWidget.setGeometry(50, 50, 100, 100); babyWidget.setAutoFillBackground(true); QPalette pal = parentWidget.palette(); pal.setColor(QPalette::Window, QColor(Qt::blue)); parentWidget.setPalette(pal); pal = childWidget.palette(); pal.setColor(QPalette::Window, QColor(Qt::white)); childWidget.setPalette(pal); pal = babyWidget.palette(); pal.setColor(QPalette::Window, QColor(Qt::red)); babyWidget.setPalette(pal); // prevent custom styles from messing up the background parentWidget.setStyle(new QWindowsStyle); babyWidget.show(); childWidget.show(); parentWidget.show(); QTest::qWaitForWindowShown(&parentWidget); QPixmap parentPixmap; QTRY_COMPARE((parentPixmap = parentWidget.windowSurface()->grabWidget(&parentWidget)).size(), QSize(300,300)); QPixmap childPixmap = childWidget.windowSurface()->grabWidget(&childWidget); QPixmap babyPixmap = babyWidget.windowSurface()->grabWidget(&babyWidget); QPixmap parentSubPixmap = parentWidget.windowSurface()->grabWidget(&parentWidget, QRect(25, 25, 100, 100)); QPixmap childSubPixmap = childWidget.windowSurface()->grabWidget(&childWidget, QRect(55, 55, 50, 50)); QPixmap childInvalidSubPixmap = childWidget.windowSurface()->grabWidget(&childWidget, QRect(-50, -50, 150, 150)); QCOMPARE(parentPixmap.size(), QSize(300, 300)); QCOMPARE(childPixmap.size(), QSize(200, 200)); QCOMPARE(babyPixmap.size(), QSize(100, 100)); QCOMPARE(parentSubPixmap.size(), QSize(100, 100)); QCOMPARE(childSubPixmap.size(), QSize(50, 50)); QCOMPARE(childInvalidSubPixmap.size(), QSize(100, 100)); QImage parentImage = parentPixmap.toImage(); QImage childImage = childPixmap.toImage(); QImage babyImage = babyPixmap.toImage(); QImage parentSubImage = parentSubPixmap.toImage(); QImage childSubImage = childSubPixmap.toImage(); QImage childInvalidSubImage = childInvalidSubPixmap.toImage(); QVERIFY(QColor(parentImage.pixel(0, 0)) == QColor(Qt::blue)); QVERIFY(QColor(parentImage.pixel(75, 75)) == QColor(Qt::white)); QVERIFY(QColor(parentImage.pixel(149, 149)) == QColor(Qt::red)); QVERIFY(QColor(childImage.pixel(0, 0)) == QColor(Qt::white)); QVERIFY(QColor(childImage.pixel(99, 99)) == QColor(Qt::red)); QVERIFY(QColor(parentSubImage.pixel(0, 0)) == QColor(Qt::blue)); QVERIFY(QColor(parentSubImage.pixel(30, 30)) == QColor(Qt::white)); QVERIFY(QColor(parentSubImage.pixel(80, 80)) == QColor(Qt::red)); QVERIFY(QColor(childSubImage.pixel(0, 0)) == QColor(Qt::red)); QVERIFY(QColor(childInvalidSubImage.pixel(0, 0)) == QColor(Qt::white)); }
//*************------------SLOTS------------************ void WindowGUI::toBinImg(){ //@TODO consider strategy pattern for binarization and making histogram //FOR NOW - create grayscale img from origin, make simple histogram, use //simplified otsu method and show img, everything in one method :( binarizeBut->setEnabled( false ); clusterBut->setEnabled( true ); qDebug() << "toBinImg slot"; //copy img, change to grayscale and make histogram, consider 8bit format QImage grayImg { originImg.convertToFormat( QImage::Format_RGB32 ) }; if ( grayImg.isNull() ){ QMessageBox::information( this, tr("Projective Clustering"), tr("cannot load")); return; } int gray{}, width{ grayImg.width() }, height { grayImg.height() }; long histogram[256] = {}; for ( int i = 0; i < width; ++i){ for ( int j = 0; j < height; ++j ){ gray = qGray( grayImg.pixel( i, j ) ) ; histogram[ gray ]++; //grayImg.setPixel( i, j, qRgb( gray, gray, gray ) ); } } //simple otsu method - use created grayscale histogram to compute threshold //theoretically need total pixels and histogram, return threshold double sum{}, sumB{}, wB{}, wF{}, mB{}, mF{}, max{}, between{}, threshold1{}, threshold2{}, results{}; long total{ ( width * height ) }; for ( int i = 1; i < 256; ++i ) sum += i * histogram[i]; for ( int i = 0; i < 256; ++i) { wB += histogram[i]; if (wB == 0) continue; wF = total - wB; if (wF == 0) break; sumB += i * histogram[i]; mB = sumB / wB; mF = (sum - sumB) / wF; between = wB * wF * qPow(mB - mF, 2); if ( between >= max ) { threshold1 = i; if ( between > max ) { threshold2 = i; } max = between; } } results = ( threshold1 + threshold2 ) / 2.0; //now change all pixel below results to white and above to black for ( int i = 0; i < width; ++i ){ for ( int j = 0; j < height; ++j ){ double avg = static_cast<double>( qGray( originImg.pixel( i, j ) )); if( results < avg ) grayImg.setPixel( i, j, qRgb( 0, 0, 0 ) ); else grayImg.setPixel( i, j, qRgb( 255, 255, 255 ) ); } } imgLab->setPixmap( QPixmap::fromImage( grayImg ) ); binImg = std::move( grayImg ); }
void PhotoBomberApp::manipulatePhoto(const QString &fileName) { QImageReader reader; // Set image name from the given file name. reader.setFileName(fileName); QImage image = getRotateImage(fileName); //reader.read(); QSize imageSize = image.size(); QColor color; // Gray it out! (this is not the gray-scale algorithm that should be used) for (int i = 0; i < imageSize.width(); i++) for (int ii = 0; ii < imageSize.height(); ii++) { color = QColor(image.pixel(i, ii)); color.setRed((color.red() + color.green() + color.blue()) / 3); color.setGreen(color.red()); color.setBlue(color.red()); image.setPixel(i, ii, color.rgb()); } // Paint an image on top of another image, so we add the gray-scaled image first. QPainter merger(&image); QString appFolder(QDir::homePath()); appFolder.chop(4); QString bomberFileName; QString bombfolder; // The aspect ratio value is used for selecting correct folder for bomber photos. float imageWidth = imageSize.width(); float imageHeight = imageSize.height(); float aspectRatio = imageWidth / imageHeight; if (aspectRatio == 1) { bombfolder = appFolder + "app/native/assets/720x720/images/bombers/"; } else { bombfolder = appFolder + "app/native/assets/images/bombers/"; } // Positions for the bombers; we need these so we can overlay the bomber image at it's correct position. // The reason for not making an image as large as the picture is so we can change resolution and or switch // between portrait/landscape if we would want to. enum positions { TOP, CENTER, BOTTOM, LEFT, RIGHT }; int vertical = RIGHT; int horizontal = BOTTOM; switch (random() % 9) { case 0: bomberFileName = bombfolder + "cow.png"; vertical = RIGHT; horizontal = CENTER; break; case 1: bomberFileName = bombfolder + "crow.png"; vertical = RIGHT; horizontal = BOTTOM; break; case 2: bomberFileName = bombfolder + "dog_2.png"; vertical = RIGHT; horizontal = BOTTOM; break; case 3: bomberFileName = bombfolder + "larsenby.png"; vertical = RIGHT; horizontal = BOTTOM; break; case 4: bomberFileName = bombfolder + "dog_1.png"; vertical = LEFT; horizontal = BOTTOM; break; case 5: bomberFileName = bombfolder + "snail.png"; vertical = LEFT; horizontal = BOTTOM; break; case 6: bomberFileName = bombfolder + "cat.png"; vertical = RIGHT; horizontal = BOTTOM; break; case 7: bomberFileName = bombfolder + "pair.png"; vertical = CENTER; horizontal = BOTTOM; break; case 8: bomberFileName = bombfolder + "seagull.png"; vertical = LEFT; horizontal = TOP; break; default: bomberFileName = bombfolder + "crow.png"; vertical = RIGHT; horizontal = BOTTOM; break; } reader.setFileName(bomberFileName); QImage bombimage = reader.read(); // Read image current size. QSize bomberImageSize = bombimage.size(); int vertical_pos; int horizontal_pos; // Vertical position if (vertical == LEFT) { vertical_pos = 0; } else if (vertical == CENTER) { vertical_pos = imageSize.width() / 2 - bomberImageSize.width() / 2; } else if (vertical == RIGHT) { vertical_pos = imageSize.width() - bomberImageSize.width(); } // Horizontal position if (horizontal == TOP) { horizontal_pos = 0; } else if (horizontal == CENTER) { horizontal_pos = imageSize.height() / 2 - bomberImageSize.height() / 2; } else if (horizontal == BOTTOM) { horizontal_pos = imageSize.height() - bomberImageSize.height(); } // Add the image and save the composition. merger.drawImage(vertical_pos, horizontal_pos, bombimage); image.save(fileName, "JPG"); // Show the photo by using this function that take use of the InvokeManager. showPhotoInCard(fileName); }
bool Game::loadLevel(int level){ QImage image; QFile data(QString("data/levels/") + QString::number(level) + ".txt"); if(!image.load(QString("data/levels/") + QString::number(level) + ".gif") || !data.open(QIODevice::ReadOnly | QIODevice::Text)) return false; QTextStream in( & data ); QStringList tmpColor = in.readLine().split(","); //odczyt linii z skladowymi koloru this->levelBackground.setRgb(tmpColor[0].toInt(), tmpColor[1].toInt(), tmpColor[2].toInt()); //ustawienie tla poziomu qglClearColor(this->levelBackground); tmpColor = in.readLine().split(","); //odczyt linii z skladowymi koloru this->hudColor.setRgb(tmpColor[0].toInt(), tmpColor[1].toInt(), tmpColor[2].toInt()); //ustawienie tla poziomu tmpColor = in.readLine().split(","); //odczyt linii z skladowymi koloru this->titleTextColor.setRgb(tmpColor[0].toInt(), tmpColor[1].toInt(), tmpColor[2].toInt()); //ustawienie tla poziomu levelWidth = image.width()*20; levelHeight = image.height()*20; CristalModel cristalModel; TileModel tileModel; tileModel.loadTexture(in.readLine()); //wczytanie tekstury na kafle C3DS *m = (C3DS*) &tileModel; C3DS m2((char*)"./data/models/kolo.3DS"); C3DS *m3 = (C3DS*) &cristalModel; this->models.clear(); this->models.append(*m); this->models.append(m2); this->models.append(*m3); QColor color; for(int x=0; x < image.width(); x++){ for(int y=0; y < image.height(); y++){ color.setRgb(image.pixel(x, y)); if(color.red() == 0 && color.green() == 255){ Cristal *power = new Cristal(); power->setModelId(2); power->setPosition(new Point3f(x*20, (image.height()-y)*20, 0)); this->cristals.append(power); } if(color.red() == 0 && color.blue() == 0 && color.green() == 0){ MapTile *tile = new MapTile(); tile->setModelId(0); tile->setPosition(new Point3f(x*20, (image.height()-y)*20, 0)); this->mapTiles.append(tile); } if(color.red() == 0 && color.green()== 0 && color.blue() == 255){ this->player.reset(); this->player.setModelId(1); this->player.setPosition(new Point3f(x*20, (image.height()-y)*20, 0)); levelTranslate.x = (levelWidth > x)? 490 : (levelWidth*0.5f)-10; levelTranslate.y = (levelHeight*0.5f)+10; } } } return true; }
bool ProcParty::checkHueButton(const QImage & imgBtn, int minHue, int maxHue, int rectMin, QRect & rect) { const int btnWidth = imgBtn.width(); const int btnHeight = imgBtn.height(); bool hasBtn = false; bool blackRect = false; for (int x = 0; x < btnWidth; x += 2) { for (int y = 0; y < btnHeight; y += 2) { QRgb rgb = imgBtn.pixel(x, y); QColor cl(rgb); if ((cl.hue() >= minHue && cl.hue() <= maxHue)) { blackRect = true; //попробовать найти маленький черный квадратик for (int rx = 0; rx < rectMin; ++rx) { for (int ry = 0; ry < rectMin; ++ry) { QRgb rgb = imgBtn.pixel(x + rx, y + ry); QColor cl(rgb); if (!(cl.hue() >= minHue && cl.hue() <= maxHue)) { //не наш пиксель rx = rectMin; blackRect = false; break; } } } if (!blackRect) { // не то ищем дальше continue; } else { //есть черный квадратик hasBtn = true; rect.setX(x); rect.setY(y); x = btnWidth; break; } } } } for (int x = rect.x(); x < btnWidth; ++x) { QRgb rgb = imgBtn.pixel(x, rect.y()); QColor cl(rgb); if (!(cl.hue() >= minHue && cl.hue() <= maxHue)) { rect.setWidth(x - rect.x()); break; } } for (int y = rect.y(); y < btnHeight; ++y) { QRgb rgb = imgBtn.pixel(rect.x(), y); QColor cl(rgb); if (!(cl.hue() >= minHue && cl.hue() <= maxHue)) { rect.setHeight(y - rect.y()); break; } } return hasBtn; }
float Trees::getHeight(int _width, int _depth, QImage _image){ QColor _pixel = _image.pixel(_width, _depth); return ((_pixel.redF()+_pixel.blueF()+_pixel.greenF())/3.0)/4.0; }
void MeshRenderer :: renderToImage(cv::Mat4b& image, int flags) { ntk_assert(m_vertex_buffer_object.initialized, "Renderer not initialized! Call setPose and setMesh."); ntk::TimeCount tc_gl_current("make_current", 2); m_pbuffer->makeCurrent(); tc_gl_current.stop(); ntk::TimeCount tc_gl_render("gl_render", 2); if (flags & WIREFRAME) glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); VertexBufferObject& vbo = m_vertex_buffer_object; glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbo.vertex_id); if (vbo.has_texcoords) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, vbo.texture_id); } else { glDisable(GL_TEXTURE_2D); } if (vbo.has_texcoords) glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vbo.has_color) glEnableClientState(GL_COLOR_ARRAY); else glColor3f(1.0f,0.f,0.f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, 0); if (vbo.has_color) glColorPointer(3, GL_UNSIGNED_BYTE, 0, ((char*) NULL) + vbo.color_offset); if (vbo.has_texcoords) glTexCoordPointer(2, GL_FLOAT, 0, ((char*) NULL) + vbo.texture_offset); if (vbo.has_faces) { glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vbo.faces_id); glNormal3f(0, 0, 1); glDrawElements(GL_TRIANGLES, vbo.nb_faces*3, GL_UNSIGNED_INT, 0); } else { glDrawArrays(GL_POINTS, 0, vbo.nb_vertices); } glDisableClientState(GL_VERTEX_ARRAY); if (vbo.has_color) glDisableClientState(GL_COLOR_ARRAY); if (vbo.has_texcoords) glDisableClientState(GL_TEXTURE_COORD_ARRAY); // bind with 0, so, switch back to normal pointer operation glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); if (vbo.has_faces) { glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glFinish(); tc_gl_render.stop(); ntk::TimeCount tc_image("to_image", 2); QImage qimage = m_pbuffer->toImage(); tc_image.stop(); ntk::TimeCount tc_depth_buffer("compute_depth_buffer", 2); computeDepthBuffer(); tc_depth_buffer.stop(); ntk::TimeCount tc_convert("convert_to_cv", 2); for (int r = 0; r < qimage.height(); ++r) for (int c = 0; c < qimage.width(); ++c) { QRgb pixel = qimage.pixel(c,r); Vec4b color (qBlue(pixel), qGreen(pixel), qRed(pixel), qAlpha(pixel)); m_color_buffer(r,c) = color; float a = qAlpha(pixel)/255.f; if (a > 0) { Vec4b old_color = image(r,c); image(r,c) = Vec4b(old_color[0]*(1-a) + color[0]*a, old_color[1]*(1-a) + color[1]*a, old_color[2]*(1-a) + color[2]*a, 255); } } tc_convert.stop(); }
void ImageProcessor::filterFigure(RectArea rect, QImage& img) { std::vector<std::vector<kaverage> > vsquare (rect.width,std::vector<kaverage>( rect.height)); int average; for(int i=0;i<rect.width;i++) { for(int j=0; j<rect.height;j++) { vsquare[i][j].Gray=qGray(img.pixel(i+rect.x,j+rect.y)); vsquare[i][j].k=0; average+=vsquare[i][j].Gray; } } average=average/(rect.width*rect.height); int CurrentLabelNumber=0; for(int i=1;i<rect.width-1;i++) { for(int j=1; j<rect.height-1;j++) { if (vsquare[i][j].Gray) { if(!vsquare[i-1][j].k && !vsquare[i][j-1].k) { CurrentLabelNumber++; vsquare[i][j].k=CurrentLabelNumber; } else if ((!vsquare[i-1][j].k && vsquare[i][j-1].k) || (vsquare[i-1][j].k && !vsquare[i][j-1].k)) { if (vsquare[i-1][j].k) {vsquare[i][j].k=vsquare[i-1][j].k;} if (vsquare[i][j-1].k) {vsquare[i][j].k=vsquare[i][j-1].k;} } else if (vsquare[i-1][j].k && vsquare[i][j-1].k) { if (vsquare[i-1][j].k == vsquare[i][j-1].k){ vsquare[i][j].k=vsquare[i][j-1].k; } else { int tmpLabel=vsquare[i-1][j].k; vsquare[i][j].k=vsquare[i][j-1].k; for(int m=1;m<rect.width-1;m++) { for(int l=1; l<rect.height-1;l++) { if (vsquare[m][l].k==tmpLabel) { vsquare[m][l].k=vsquare[i][j-1].k; } } } } } } } } std::vector<int> GkArea(CurrentLabelNumber+1,0); for(int i=1;i<rect.width-1;i++) { for(int j=1; j<rect.height-1;j++) { if (vsquare[i][j].k!=0) GkArea[vsquare[i][j].k]++; } } int MaxK=0; int ThisK=0; for (int i=1; (static_cast<unsigned int>(i))<GkArea.size(); i++) { if (GkArea[i]>MaxK) { MaxK=GkArea[i]; ThisK=i; } } for(int i=1;i<rect.width-1;i++) { for(int j=1; j<rect.height-1;j++) { if (vsquare[i][j].k!=ThisK) {vsquare[i][j].k=0;} else if (GkArea[vsquare[i][j].k]<100) {vsquare[i][j].k=0;} } } for(int i=1;i<rect.width-1;i++) { for(int j=1; j<rect.height-1;j++) { img.setPixel(rect.x+i,rect.y+j,vsquare[i][j].k?0xffffff:0x000000 //0xffffff*vsquare[i][j].k/(CurrentLabelNumber+2) ); } } if (DebugMode) { sendImage(*image); writeLog(QString(tr("Finding compact spaces."))); } }
void MaskWidget::paintEvent(QPaintEvent* e) { if (!m_desktopPixmap.isNull()) { m_curPos = QCursor::pos(); QPainter painter(this); painter.drawPixmap(0, 0, m_desktopPixmap); if (!m_bScreenShotDone) { if (!m_bDragging) { m_curRc.setRect(-9999, -9999, 19999, 19999); for (std::vector<RECT>::iterator it = g_winRects.begin(); it != g_winRects.end(); ++it) { QRect rect; rect.setRect(it->left, it->top, it->right - it->left, it->bottom - it->top); if (rect.contains(QCursor::pos()) && m_curRc.contains(rect)/* && rect.height() > 5 && rect.width() > 5*/) { m_curRc = rect; //break; } } } else { m_curRc = QRect(m_startPoint, QCursor::pos()); } } painter.save(); painter.setPen(Qt::NoPen); painter.setBrush(QColor(0, 0, 0, 120)); QPolygon p1(QRect(0, 0, width(), height())); QPolygon p2(m_curRc, true); p1 = p1.subtracted(p2); painter.drawPolygon(p1); painter.restore(); painter.save(); QPen pen = painter.pen(); if (m_bScreenShotDone || m_bMousePressing) { pen.setWidth(2); pen.setColor(QColor(6, 157, 213)); pen.setStyle(Qt::DashDotDotLine); } else { pen.setWidth(4); pen.setColor(QColor(0, 255, 0)); pen.setStyle(Qt::SolidLine); } painter.setPen(pen); painter.drawRect(m_curRc); painter.restore(); painter.save(); QRect ori(m_curPos.x() - 15, m_curPos.y() - 11, 30, 22); QPixmap magnifier(126, 122); QPainter painter2(&magnifier); painter2.save(); painter2.fillRect(0, 0, 126, 122, QBrush(QColor(51, 51, 51, 200))); painter2.restore(); QPen p = painter2.pen(); p.setWidth(1); p.setColor(QColor(51, 51, 51)); painter2.setPen(p); painter2.drawRect(0, 0, 125, 93); p.setWidth(2); p.setColor(QColor(255, 255, 255)); painter2.setPen(p); painter2.drawRect(2, 2, 122, 90); painter2.drawPixmap(3, 3, m_desktopPixmap.copy(ori).scaled(120, 88)); p.setWidth(4); p.setColor(QColor(0, 122, 179, 128)); painter2.setPen(p); painter2.drawLine(5, 45, 121, 45); painter2.drawLine(61, 5, 61, 89); p.setWidth(1); p.setColor(QColor(255, 255, 255)); painter2.setPen(p); painter2.drawText(6, 105, QString("%1 x %2").arg(m_curRc.width()).arg(m_curRc.height())); QImage image = m_desktopPixmap.toImage(); QRgb rgb = image.pixel(m_curPos.x()-1, m_curPos.y()-1); painter2.drawText(6, 118, QString("rgb(%1,%2,%3").arg(qRed(rgb)).arg(qGreen(rgb)).arg(qBlue(rgb))); QPoint showPoint(m_curPos.x() + 10, m_curPos.y() + 10); if (m_curPos.y() + 130 > this->height()) showPoint.setY(m_curPos.y() - 130); if (m_curPos.x() + 130 > this->width()) showPoint.setX(m_curPos.x() - 130); painter.drawPixmap(showPoint, magnifier); } }
//===========================================================================// // void ImageOperations::subsample(QImage image, QImage* ret, // // bool resize = true) // //===========================================================================// // INPUTS: image: QImage to be sub-sampled by factor 2. // // resize: flag to indicate whether the size of the image should // // be decreased by factor 2 as part of sub-sampling or // // pixel values duplicated to maintain the original size. // // OUTPUTS: QImage: Sub-sampled image of either equal or half the original // // size. // // OPERATION: The average of a pixel and its right, lower and lower-right // // neighbours is computed and used as value for the pixel(s) in // // the sub-sampled image. // //===========================================================================// void ImageOperations::subsample( const QImage& qimg, QImage& qimgRet, bool bResize) { int subs_w, subs_h; if( bResize ) { // Compute the subs_w = int(qimg.width()/2); // size of the subs_h = int(qimg.height()/2); // output image. } else { subs_w = qimg.width(); subs_h = qimg.height(); } qimgRet.create(subs_w, subs_h, 32); int col_r, col_g, col_b; for (int y=0; y<qimg.height(); y+=2) { // Traverse image for (int x=0; x<qimg.width(); x+=2) { // and compute col_r = qRed(qimg.pixel(x,y)); // average of col_g = qGreen(qimg.pixel(x,y)); // the pixel and col_b = qBlue(qimg.pixel(x,y)); // its neighbours int sum = 1; // to the right, if (x < qimg.width()-1) { // the bottom as col_r += qRed (qimg.pixel(x+1, y)); // well as the col_g += qGreen(qimg.pixel(x+1,y)); // bottom-right. col_b += qBlue (qimg.pixel(x+1,y)); // Consider image sum++; // borders. } if (y < qimg.height()-1) { col_r += qRed (qimg.pixel(x,y+1)); col_g += qGreen(qimg.pixel(x,y+1)); col_b += qBlue (qimg.pixel(x,y+1)); sum++; } if ((x<qimg.width()-1) && (y<qimg.height()-1)) { col_r += qRed (qimg.pixel(x+1, y+1)); col_g += qGreen(qimg.pixel(x+1, y+1)); col_b += qBlue (qimg.pixel(x+1, y+1)); sum++; } col_r /= sum; col_g /= sum; col_b /= sum; if (bResize) { // Set the output if ((int(x/2) < subs_w) && (int(y/2) < subs_h)) { // image's pixels qimgRet.setPixel(int(x/2), int(y/2), // to the computed qRgb(col_r, col_g, col_b)); // values. } } else { // In the case that qimgRet.setPixel(x, y, qRgb(col_r, col_g, // the image is col_b)); // not being re- if (x < qimg.width()-1) { // sized, four qimgRet.setPixel(x+1, y, qRgb(col_r, col_g, // pixels hold col_b)); // the same value } // (with the if (y < qimg.height()-1) { // exception of qimgRet.setPixel(x, y+1, qRgb(col_r, col_g, // the borders). col_b)); } if ((x<qimg.width()-1) && (y<qimg.height()-1)) { qimgRet.setPixel(x+1, y+1, qRgb(col_r, col_g, col_b)); } } } } }
bool VoxelTree::readFromSquareARGB32Pixels(const char* filename) { emit importProgress(0); int minAlpha = INT_MAX; QImage pngImage = QImage(filename); for (int i = 0; i < pngImage.width(); ++i) { for (int j = 0; j < pngImage.height(); ++j) { minAlpha = std::min(qAlpha(pngImage.pixel(i, j)) , minAlpha); } } int maxSize = std::max(pngImage.width(), pngImage.height()); int scale = 1; while (maxSize > scale) {scale *= 2;} float size = 1.0f / scale; emit importSize(size * pngImage.width(), 1.0f, size * pngImage.height()); QRgb pixel; int minNeighborhoodAlpha; for (int i = 0; i < pngImage.width(); ++i) { for (int j = 0; j < pngImage.height(); ++j) { emit importProgress((100 * (i * pngImage.height() + j)) / (pngImage.width() * pngImage.height())); pixel = pngImage.pixel(i, j); minNeighborhoodAlpha = qAlpha(pixel) - 1; if (i != 0) { minNeighborhoodAlpha = std::min(minNeighborhoodAlpha, qAlpha(pngImage.pixel(i - 1, j))); } if (j != 0) { minNeighborhoodAlpha = std::min(minNeighborhoodAlpha, qAlpha(pngImage.pixel(i, j - 1))); } if (i < pngImage.width() - 1) { minNeighborhoodAlpha = std::min(minNeighborhoodAlpha, qAlpha(pngImage.pixel(i + 1, j))); } if (j < pngImage.height() - 1) { minNeighborhoodAlpha = std::min(minNeighborhoodAlpha, qAlpha(pngImage.pixel(i, j + 1))); } while (qAlpha(pixel) > minNeighborhoodAlpha) { ++minNeighborhoodAlpha; createVoxel(i * size, (minNeighborhoodAlpha - minAlpha) * size, j * size, size, qRed(pixel), qGreen(pixel), qBlue(pixel), true); } } } emit importProgress(100); return true; }
//===========================================================================// // void ImageOperations::edgeSobel(QImage image, QImage* ret, int thresh) // //===========================================================================// // INPUTS: image: QImage whose edges are to be detected. // // thresh: integer value above which a gradient difference will // // be classified as an edge. // // OUTPUTS: QImage: image containing the detected edges as feature points // // which are marked by a value of RGB = 000. All other regions // // of the output image have the value 255/255/255. // // OPERATION: The approximation to the two Sobel convolution matrixes is // // used which computes the gradient value of a pixel in a single // // pass. Then the passed threshold is applied to those values and // // the output image generated accordingly. // //===========================================================================// void ImageOperations::edgeSobel( const QImage& qimg, QImage& qimgRet, int nThresh ) { qimgRet = qimg.copy(); for( int y=0; y < qimg.height(); y++ ) { // Traverse image for( int x=0; x < qimg.width(); x++ ) { // and compute // grayscale int val = 0; // gradient value if( (x>0) && (y>0) ) // taking into val += qGray(qimg.pixel(x-1, y-1)); // consideration if( y>0 ) // the edges. val += 2*qGray(qimg.pixel(x, y-1)); // (later the if( (x<qimg.width()-1) && (y>0) ) // edge values val += qGray(qimg.pixel(x+1, y-1)); // will be over- if( (x>0) && (y<qimg.height()-1) ) // written by non- val -= qGray(qimg.pixel(x-1, y+1)); // features). if( y<qimg.height()-1 ) // val -= 2*qGray(qimg.pixel(x, y+1)); // if( (x<qimg.width()-1) && (y<qimg.height()-1) ) // val -= qGray(qimg.pixel(x+1, y+1)); // val = abs(val); // int val2 = 0; if( (x<qimg.width()-1) && (y>0) ) val2 += qGray(qimg.pixel(x+1, y-1)); if( x<qimg.width()-1 ) val2 += 2*qGray(qimg.pixel(x+1, y)); if( (x<qimg.width()-1) && (y<qimg.height()-1) ) val2 += qGray(qimg.pixel(x+1, y+1)); if( (x>0) && (y>0) ) val2 -= qGray(qimg.pixel(x-1, y-1)); if( x>0 ) val2 -= 2*qGray(qimg.pixel(x-1, y)); if( (x>0) && (y<qimg.height()-1) ) val2 -= qGray(qimg.pixel(x-1, y+1)); val2 = abs(val2); val += val2; if (val > 255) val = 255; if (nThresh == 0) { // If thresh=0, qimgRet.setPixel(x, y, qRgb(val, val, val)); // output value. } else { // Normal case: if( (val >= nThresh) && // If Threshold (x != 0) && (x != qimg.width()-1) && // surpassed and (y != 0) && (y != qimg.height()-1)) { // not on the qimgRet.setPixel(x, y, qRgb(0, 0, 0)); // border, set // feature. } else { // Else set non- qimgRet.setPixel(x, y, qRgb(255, 255, 255)); // feature. } } } } }
void MainWindow::timerDone() { if (!working) { working = true; int result; while((result = video_next(cur)) < -1); if(result != -1) { if (result == 0) { counter++; ui->statusBar->showMessage(QString("%1").arg(counter) + " frames processed."); QImage img(cur->pDat->data[0], cur->width, cur->height, QImage::Format_ARGB32); QBitmap bmp; bmp.fromData(QSize(cur->width, cur->height), cur->pDat->data[0]); QColor color; QColor avgColor; double avgColorRed = 0; double avgColorGreen = 0; double avgColorBlue = 0; QColor avgColortl; double avgColorRedtl = 0; double avgColorGreentl = 0; double avgColorBluetl = 0; QColor avgColortr; double avgColorRedtr = 0; double avgColorGreentr = 0; double avgColorBluetr = 0; QColor avgColorbl; double avgColorRedbl = 0; double avgColorGreenbl = 0; double avgColorBluebl = 0; QColor avgColorbr; double avgColorRedbr = 0; double avgColorGreenbr = 0; double avgColorBluebr = 0; QColor brightness; double avg = 0; double diffRed = 0; double diffGreen = 0; double diffBlue = 0; double moodRed = 0; double moodGreen = 0; double moodBlue = 0; for (int w = 0; w < img.width(); w++) { for (int h = 0; h < img.height(); h++) { color = img.pixel(QPoint(w,h)); if (w < img.width() / 2 && h < img.height() / 2) { avgColorRedtl += color.red(); avgColorGreentl += color.green(); avgColorBluetl += color.blue(); } else if (w > img.width() / 2 && h < img.height() / 2) { avgColorRedtr += color.red(); avgColorGreentr += color.green(); avgColorBluetr += color.blue(); } else if (w < img.width() / 2 && h > img.height() / 2) { avgColorRedbl += color.red(); avgColorGreenbl += color.green(); avgColorBluebl += color.blue(); } else if (w > img.width() / 2 && h > img.height() / 2) { avgColorRedbr += color.red(); avgColorGreenbr += color.green(); avgColorBluebr += color.blue(); } avgColorRed += color.red(); avgColorGreen += color.green(); avgColorBlue += color.blue(); avg += ((color.red() + color.green() + color.blue()) / 3); if (!imageSave.isNull() && (int)counter % 2) { QColor subtractColor = imageSave.pixel(QPoint(w,h)); diffRed += color.red(); diffGreen += color.green(); diffBlue += color.blue(); } // MoodBar if (h < img.height() / 3) { moodRed += color.red(); } else if (h > (img.height() / 3) *2) { moodBlue += color.green(); } else { moodGreen += color.blue(); } } } // Average Color (Whole Image) avgColor.setRed(avgColorRed / (img.width() * img.height())); avgColor.setGreen(avgColorGreen / (img.width() * img.height())); avgColor.setBlue(avgColorBlue / (img.width() * img.height())); avgColorList << avgColor; QImage avgColorDisplayImage(avgColorList.size(),20,QImage::Format_RGB32); QPainter a(&avgColorDisplayImage); for (int i = 0; i < avgColorList.size(); i+=1) { QPen chPen(avgColorList.at(i), 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); a.setPen(chPen); a.drawLine(i, 0, i, 20); } ui->averageDisplay->setPixmap(QPixmap::fromImage(avgColorDisplayImage)); ui->averageDisplay->setMaximumSize(ui->pushButton_2->window()->width() - 50, 20); // Average Color (Quad) avgColortl.setRed(avgColorRedtl / ((img.width() / 2) * (img.height() / 2))); avgColortl.setGreen(avgColorGreentl / ((img.width() / 2) * (img.height() / 2))); avgColortl.setBlue(avgColorBluetl / ((img.width() / 2) * (img.height() / 2))); avgColortr.setRed(avgColorRedtr / ((img.width() / 2) * (img.height() / 2))); avgColortr.setGreen(avgColorGreentr / ((img.width() / 2) * (img.height() / 2))); avgColortr.setBlue(avgColorBluetr / ((img.width() / 2) * (img.height() / 2))); avgColorbl.setRed(avgColorRedbl / ((img.width() / 2) * (img.height() / 2))); avgColorbl.setGreen(avgColorGreenbl / ((img.width() / 2) * (img.height() / 2))); avgColorbl.setBlue(avgColorBluebl / ((img.width() / 2) * (img.height() / 2))); avgColorbr.setRed(avgColorRedbr / ((img.width() / 2) * (img.height() / 2))); avgColorbr.setGreen(avgColorGreenbr / ((img.width() / 2) * (img.height() / 2))); avgColorbr.setBlue(avgColorBluebr / ((img.width() / 2) * (img.height() / 2))); if (avgColortl.isValid() && avgColortr.isValid() && avgColorbl.isValid() && avgColorbr.isValid()) { avgColorQuadListtl << avgColortl; avgColorQuadListtr << avgColortr; avgColorQuadListbl << avgColorbl; avgColorQuadListbr << avgColorbr; } QImage avgColorQuadDisplayImage(avgColorQuadListtl.size(),40,QImage::Format_RGB32); QPainter q(&avgColorQuadDisplayImage); for (int i = 0; i < avgColorQuadListtl.size(); i++) { QPen chPen(avgColorQuadListtl.at(i), 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); q.setPen(chPen); q.drawLine(i, 0, i, 10); chPen.setColor(avgColorQuadListtr.at(i)); q.setPen(chPen); q.drawLine(i, 10, i, 20); chPen.setColor(avgColorQuadListbl.at(i)); q.setPen(chPen); q.drawLine(i, 20, i, 30); chPen.setColor(avgColorQuadListbr.at(i)); q.setPen(chPen); q.drawLine(i, 30, i, 40); } ui->averageQuadDisplay->setPixmap(QPixmap::fromImage(avgColorQuadDisplayImage)); ui->averageQuadDisplay->setMaximumSize(ui->pushButton_2->window()->width() - 50,40); // Brightness (Grayscale) avg = avg / (img.width() * img.height()); brightness.setRed(avg); brightness.setGreen(avg); brightness.setBlue(avg); brightnessList << brightness; QImage brightnessDisplayImage(brightnessList.size(),20,QImage::Format_RGB32); QPainter b(&brightnessDisplayImage); for (int i = 0; i < brightnessList.size(); i++) { QPen chPen(brightnessList.at(i), 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); b.setPen(chPen); b.drawLine(i, 0, i, 20); } ui->brightnessDisplay->setPixmap(QPixmap::fromImage(brightnessDisplayImage)); ui->brightnessDisplay->setMaximumSize(ui->pushButton_2->window()->width() - 50, 20); // Difference QColor colorSubtract = avgColorList.at(avgColorList.length() - 1); difference.setRed(abs(avgColorRed-diffRed) / (img.width() * img.height())); difference.setGreen(abs(avgColorGreen-diffGreen) / (img.width() * img.height())); difference.setBlue(abs(avgColorBlue-diffBlue) / (img.width() * img.height())); if (difference.isValid()) differenceList << difference; QImage differenceDisplayImage(differenceList.size(),20,QImage::Format_RGB32); QPainter d(&differenceDisplayImage); for (int i = 0; i < differenceList.size(); i++) { QPen chPen(differenceList.at(i), 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); d.setPen(chPen); d.drawLine(i, 0, i, 20); } ui->differenceDisplay->setPixmap(QPixmap::fromImage(differenceDisplayImage)); ui->differenceDisplay->setMaximumSize(ui->pushButton_2->window()->width() - 50, 20); // MoodBar QColor moodBarColor; double total = 255; double faktorMax = (((img.height() / 3) * img.width()) * 255); double faktor = total / faktorMax; moodBarColor.setRed(moodRed * faktor); moodBarColor.setGreen(moodGreen * faktor); moodBarColor.setBlue(moodBlue * faktor); if (moodBarColor.isValid()) moodList << moodBarColor; QImage moodDisplayImage(moodList.size(),20,QImage::Format_RGB32); QPainter g(&moodDisplayImage); for (int j = 0; j < moodList.size(); j++) { QPen chPen(moodList.at(j), 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); g.setPen(chPen); g.drawLine(j, 0, j, 20); } ui->moodDisplay->setPixmap(QPixmap::fromImage(moodDisplayImage)); ui->moodDisplay->setMaximumSize(ui->pushButton_2->window()->width() - 50, 20); // Video view ui->label->setPixmap(QPixmap::fromImage(img)); ui->label->show(); ui->pushButton_2->update(); ui->label->update(); if ((int)counter % 2) imageSave = img; qApp->processEvents(); } } else { ui->pushButton_2->setText("Start Analysis"); ui->pushButton->setEnabled(false); working = false; timer->stop(); } working = false; } }
QImage ExtraFiltersPlugin::filterImage(const QString &filter, const QImage &image, QWidget *parent) { QImage original = image.convertToFormat(QImage::Format_RGB32); QImage result = original; if (filter == tr("Flip Horizontally")) { for (int y = 0; y < original.height(); ++y) { for (int x = 0; x < original.width(); ++x) { int pixel = original.pixel(original.width() - x - 1, y); result.setPixel(x, y, pixel); } } } else if (filter == tr("Flip Vertically")) { for (int y = 0; y < original.height(); ++y) { for (int x = 0; x < original.width(); ++x) { int pixel = original.pixel(x, original.height() - y - 1); result.setPixel(x, y, pixel); } } } else if (filter == tr("Smudge...")) { bool ok; int numIters = QInputDialog::getInteger(parent, tr("Smudge Filter"), tr("Enter number of iterations:"), 5, 1, 20, 1, &ok); if (ok) { for (int i = 0; i < numIters; ++i) { for (int y = 1; y < original.height() - 1; ++y) { for (int x = 1; x < original.width() - 1; ++x) { int p1 = original.pixel(x, y); int p2 = original.pixel(x, y + 1); int p3 = original.pixel(x, y - 1); int p4 = original.pixel(x + 1, y); int p5 = original.pixel(x - 1, y); int red = (qRed(p1) + qRed(p2) + qRed(p3) + qRed(p4) + qRed(p5)) / 5; int green = (qGreen(p1) + qGreen(p2) + qGreen(p3) + qGreen(p4) + qGreen(p5)) / 5; int blue = (qBlue(p1) + qBlue(p2) + qBlue(p3) + qBlue(p4) + qBlue(p5)) / 5; int alpha = (qAlpha(p1) + qAlpha(p2) + qAlpha(p3) + qAlpha(p4) + qAlpha(p5)) / 5; result.setPixel(x, y, qRgba(red, green, blue, alpha)); } } } } } else if (filter == tr("Threshold...")) { bool ok; int threshold = QInputDialog::getInteger(parent, tr("Threshold Filter"), tr("Enter threshold:"), 10, 1, 256, 1, &ok); if (ok) { int factor = 256 / threshold; for (int y = 0; y < original.height(); ++y) { for (int x = 0; x < original.width(); ++x) { int pixel = original.pixel(x, y); result.setPixel(x, y, qRgba(qRed(pixel) / factor * factor, qGreen(pixel) / factor * factor, qBlue(pixel) / factor * factor, qAlpha(pixel))); } } } } return result; }
void tst_QOpenGL::QTBUG15621_triangulatingStrokerDivZero() { #if defined(Q_OS_LINUX) && defined(Q_CC_GNU) && !defined(__x86_64__) QSKIP("QTBUG-22617"); #endif QWindow window; window.setSurfaceType(QWindow::OpenGLSurface); window.setGeometry(0, 0, 128, 128); window.create(); QOpenGLContext ctx; ctx.create(); ctx.makeCurrent(&window); if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects()) QSKIP("QOpenGLFramebufferObject not supported on this platform"); QOpenGLFramebufferObject fbo(128, 128); fbo.bind(); QOpenGLPaintDevice device(128, 128); // QTBUG-15621 is only a problem when qreal is double, but do the test anyway. qreal delta = sizeof(qreal) == sizeof(float) ? 1e-4 : 1e-8; QVERIFY(128 != 128 + delta); QPainterPath path; path.moveTo(16 + delta, 16); path.moveTo(16, 16); path.lineTo(16 + delta, 16); // Short lines to check for division by zero. path.lineTo(112 - delta, 16); path.lineTo(112, 16); path.quadTo(112, 16, 112, 16 + delta); path.quadTo(112, 64, 112, 112 - delta); path.quadTo(112, 112, 112, 112); path.cubicTo(112, 112, 112, 112, 112 - delta, 112); path.cubicTo(80, 112, 48, 112, 16 + delta, 112); path.cubicTo(16 + delta, 112, 16 + delta, 112, 16, 112); path.closeSubpath(); QPen pen(Qt::red, 28, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); QPainter p(&device); p.fillRect(QRect(0, 0, 128, 128), Qt::blue); p.strokePath(path, pen); p.end(); QImage image = fbo.toImage().convertToFormat(QImage::Format_RGB32); const QRgb red = 0xffff0000; const QRgb blue = 0xff0000ff; QCOMPARE(image.pixel(8, 8), red); QCOMPARE(image.pixel(119, 8), red); QCOMPARE(image.pixel(8, 119), red); QCOMPARE(image.pixel(119, 119), red); QCOMPARE(image.pixel(0, 0), blue); QCOMPARE(image.pixel(127, 0), blue); QCOMPARE(image.pixel(0, 127), blue); QCOMPARE(image.pixel(127, 127), blue); QCOMPARE(image.pixel(32, 32), blue); QCOMPARE(image.pixel(95, 32), blue); QCOMPARE(image.pixel(32, 95), blue); QCOMPARE(image.pixel(95, 95), blue); }
MLP::Vector RankClassifier::BinarizeImageSV( const QImage& img, float maxSaturation, float minValue ) { MLP::Vector bin( img.width() * img.height() ); float sumX = 0.0f; float sumY = 0.0f; int area = 0; for( int y = 0; y < img.height(); y++ ) { for( int x = 0; x < img.width(); x++ ) { int idx = y * img.width() + x; QRgb pixel = img.pixel( x, y ); int h, s, v; QColor( pixel ).getHsv( &h, &s, &v ); h = std::max(0, h); s = int(float(s) / 255.0f * 100.0f); v = int(float(v) / 255.0f * 100.0f); bool white = ( s <= maxSaturation && v >= minValue ); bin[ idx ] = white ? 1.0f : 0.0f; if( white ) { sumX += (float(x) + 0.5f); sumY += (float(y) + 0.5f); area++; } } } MLP::Vector binCentered( img.width() * img.height(), 0.0f ); float imageCenterX = img.width() * 0.5f; float imageCenterY = img.height() * 0.5f; float gravityX = area ? sumX / area : imageCenterX; float gravityY = area ? sumY / area : imageCenterY; int offsetX = std::round(imageCenterX - gravityX); int offsetY = std::round(imageCenterY - gravityY); for( int y = 0; y < img.height(); y++ ) { for( int x = 0; x < img.width(); x++ ) { int idx = y * img.width() + x; float val = bin[ idx ]; int newX = x + offsetX; int newY = y + offsetY; if( newX >= 0 && newX < img.width() && newY >= 0 && newY < img.height() ) { int newIdx = newY * img.width() + newX; binCentered[ newIdx ] = val; } } } return binCentered; }
void renderWatermark(QImage & image, const QString & wmText, const QFont & wmFont, const unsigned int wmOpacity, double pA, double pB, double pC, double pD) { const double pi = 3.14159265358979323846; double w = ((double)image.width() - pA); double h = ((double)image.height() - pB); double theta = (pi/-2.0) + atan(w / h); double l = sqrt((w * w) + (h * h)); const double sintheta = sin(theta); const double costheta = cos(theta); double margin_width = pC; double margin_height = pD; int offset = (int)(l * 0.05); int l2 = (int)(l * 0.9); int x = (int)(sintheta * h) + offset; int y = (int)(costheta * h); QFont fnt = wmFont; QFontMetrics fm = QFontMetrics(fnt); QFontInfo fi(fnt); QString family = fi.family(); QList<int> sizes = QFontDatabase().pointSizes(family); qSort(sizes); for(int i = sizes.size() - 1; i > 0; i--) { fnt.setPointSize(sizes[i]); fm = QFontMetrics(fnt); if(fm.boundingRect(wmText).width() < l2) break; } int fh = fm.height(); y = y - (fh/2); //NB QPixmap not safe outside of main thread, using QImage instead QImage wm(image.width(), image.height(), QImage::Format_RGB32); wm.fill(0xFFFFFFFF); QPainter pPainter; pPainter.begin(&wm); pPainter.setFont(fnt); pPainter.translate(margin_width, margin_height); pPainter.rotate((theta/pi)*180); pPainter.drawText(x, y, l2, fh, Qt::AlignCenter, wmText); pPainter.end(); double opacity = wmOpacity / 255.0; double opacity_inv = 1.0 - opacity; QRgb s = 0; QRgb d = 0; for(y = 0; y < image.height(); y++) { for(x = 0; x < image.width(); x++) { s = wm.pixel(x, y); if((s & 0x00ffffff) == 0x00ffffff) continue; // if it's white just skip it d = image.pixel(x, y); image.setPixel(x, y, qRgb( (int)((qRed(s) * opacity) + (qRed(d) * opacity_inv)), (int)((qGreen(s) * opacity) + (qGreen(d) * opacity_inv)), (int)((qBlue(s) * opacity) + (qBlue(d) * opacity_inv)) )); } } }
// // load image and store into opengl texture // memorize image size // bool frag_pane::loadImage( const QString strFile ) { bool bRetCode = false; QImage img; QRgb value; QImageReader reader; int k, iRow, i, j; int nWidth, nHeight; #ifdef _DEBUG QImage img2; #endif // _DEBUG GLubyte *image = NULL; // *** Load Image *** // load image using QImageReader // set image pixels to one-dimensional 8-bit RGBA buffer reader.setFileName( strFile ); if( !reader.canRead( ) ) { qDebug() << "ERROR! Failed to load image " << strFile; goto PIX_EXIT; } if( !reader.read( &img ) ) { qDebug() << "ERROR! Failed to read image " << strFile; goto PIX_EXIT; } nWidth = img.width( ); nHeight = img.height( ); image = new GLubyte[nHeight*nWidth*4]; if( !image ) { qDebug() << "ERROR! Memory Allocation Failed."; goto PIX_EXIT; } // to display the texture directory onto pane, set the buffer upside down // to copy on FBO, use the image orientation as it is for( i = 0; i < nHeight; i++ ) { iRow = nHeight - i - 1; //iRow = i; for( j = 0 ; j < nWidth ; j++ ) { k = i * nWidth + j; value = img.pixel( j, iRow ); image[k*4] = qRed( value ); image[k*4+1] = qGreen( value ); image[k*4+2] = qBlue( value ); image[k*4+3] = 255; } } // create(or re-create) the FBO to set the loaded image if( _in_fbo ) { delete _in_fbo; _in_fbo = NULL; } makeCurrent( ); _in_fbo = new QGLFramebufferObject( nWidth, nHeight, GL_TEXTURE_2D ); if( !_in_fbo ) { goto PIX_EXIT; } // set the buffer into texture glEnable( GL_TEXTURE_2D ); _in_fbo->bind( ); glEnable( GL_TEXTURE_2D ); glViewport( 0, 0, nWidth, nHeight ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho( 0.0, nWidth, 0.0, nHeight, -1.0, 1.0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); glBindTexture( GL_TEXTURE_2D, _in_fbo->texture( ) ); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); _in_fbo->release(); // --- DONE --- bRetCode = true; PIX_EXIT: if( image ) { delete[] image; image = NULL; } return bRetCode; }
/* Main method. * Opening file. * Creating binary pixel array. * Counting the number of silhouettes on the image by calling main logic method. * Printing the binary array into the file if debug == true. */ int main(){ /* Open image */ if (FILENAME == " ") { cout << " Please enter the path to your file: "; getline(cin, FILENAME); } if (debug) { cout << "d: Initiated opening the image file." << endl; } QImage* image = loadImage(); if (debug) { cout << "d: Image file successfully open." << endl; } if(debug){ cout << "d: Image width: " << image->width()<<endl; cout << "d: Image height: " << image->height()<<endl; } int imgHeight = image->height(); int imgWidth = image->width(); /* Calculating the MINIMUM_SILHOUETTE_SIZE given the image size */ MINIMUM_SILHOUETTE_SIZE = (imgHeight*imgWidth) * MINIMUM_SILHOUETTE_SIZE; /* Creating pixel array */ if (debug) { cout << "d: Initiated the creation of the array.." << endl; } //initializing int **pixelArray; pixelArray = new int *[imgHeight]; for (int i=0; i < imgHeight; i++) { pixelArray[i] = new int[imgWidth]; } //filling //imageBinarization(pixelArray, imgHeight, imgWidth); /// NOTE! QImage pixel( col , row ) for (int i = 0; i < imgHeight; i++) { //rows for (int j = 0; j < imgWidth; j++) { //cols /* First binarization method.*/ QColor curPixCol = image->pixel(j, i); if (curPixCol.lightness() >= LIGHTNESS) { pixelArray[i][j] = 0; } else { pixelArray[i][j] = 1; } } } if (debug) { cout << "d: Array created successfully." << endl; } /* Counting the number of objects on the image */ if (debug) { cout << "d: Initiated the counting of the number of silhouettes.." << endl; } int count = getCountOfObj(pixelArray, imgHeight, imgWidth); if (debug) { cout << "d: Counting of the number completed." << endl; } if (debug && createFile_debug) { cout << "d: cf: Initiated the writing binary array into file.." << endl; ///just to see how it looks. QFile file("silhouettes.txt"); QTextStream out(&file); if(file.open(QIODevice::Append)) { for (int i = 0; i < imgHeight; i++) { for (int j = 0; j < imgWidth; j++) { if (pixelArray[i][j] == 0) { out << "-"; } else { out << pixelArray[i][j]; } } out << endl; } } file.close(); cout << "d: cf: Binary array successfully written into the file.." << endl; } /* Clear memory */ if (debug) { cout << "d: Initiated the clearing the memory.." << endl; } for (int i=0; i < imgHeight; i++) { delete pixelArray[i]; } delete [] pixelArray; delete image; if (debug) { cout << "d: Memory successfully cleared.." << endl; } /* Done! */ if (debug) { cout << endl << endl; } cout << " The number of silhouettes: " << count << endl; system("pause"); return 0; }
bool Arc3DModel::BuildMesh(CMeshO &m, int subsampleFactor, int minCount, float minAngleCos, int smoothSteps, bool dilation, int dilationPasses, int dilationSize, bool erosion, int erosionPasses, int erosionSize,float scalingFactor) { FloatImage depthImgf; CharImage countImgc; clock(); depthImgf.Open(depthName.toUtf8().data()); countImgc.Open(countName.toUtf8().data()); QImage TextureImg; TextureImg.load(textureName); clock(); CombineHandMadeMaskAndCount(countImgc,maskName); // set count to zero for all masked points FloatImage depthSubf; // the subsampled depth image FloatImage countSubf; // the subsampled quality image (quality == count) SmartSubSample(subsampleFactor,depthImgf,countImgc,depthSubf,countSubf,minCount); CharImage FeatureMask; // the subsampled image with (quality == features) GenerateGradientSmoothingMask(subsampleFactor, TextureImg, FeatureMask); depthSubf.convertToQImage().save("tmp_depth.jpg", "jpg"); clock(); float depthThr = ComputeDepthJumpThr(depthSubf,0.8f); for(int ii=0;ii<smoothSteps;++ii) Laplacian2(depthSubf,countSubf,minCount,FeatureMask,depthThr); clock(); vcg::tri::Grid<CMeshO>(m,depthSubf.w,depthSubf.h,depthImgf.w,depthImgf.h,&*depthSubf.v.begin()); clock(); // The depth is filtered and the minimum count mask is update accordingly. // To be more specific the border of the depth map are identified by erosion // and the relative vertex removed (by setting mincount equal to 0). float depthThr2 = ComputeDepthJumpThr(depthSubf,0.95f); depthFilter(depthSubf, countSubf, depthThr2, dilation, dilationPasses, dilationSize, erosion, erosionPasses, erosionSize); int vn = m.vn; for(int i=0;i<vn;++i) if(countSubf.v[i]<minCount) { m.vert[i].SetD(); m.vn--; } cam.Open(cameraName.toUtf8().data()); CMeshO::VertexIterator vi; Matrix33d Rinv= Inverse(cam.R); for(vi=m.vert.begin();vi!=m.vert.end();++vi)if(!(*vi).IsD()) { Point3m in=(*vi).P(); Point3d out; cam.DepthTo3DPoint(in[0], in[1], in[2], out); (*vi).P().Import(out); QRgb c = TextureImg.pixel(int(in[0]), int(in[1])); vcg::Color4b tmpcol(qRed(c),qGreen(c),qBlue(c),0); (*vi).C().Import(tmpcol); if(FeatureMask.Val(int(in[0]/subsampleFactor), int(in[1]/subsampleFactor))<200) (*vi).Q()=0; else (*vi).Q()=1; (*vi).Q()=float(FeatureMask.Val(in[0]/subsampleFactor, in[1]/subsampleFactor))/255.0; } clock(); CMeshO::FaceIterator fi; Point3m CameraPos = Point3m::Construct(cam.t); for(fi=m.face.begin();fi!=m.face.end();++fi) { if((*fi).V(0)->IsD() ||(*fi).V(1)->IsD() ||(*fi).V(2)->IsD() ) { (*fi).SetD(); --m.fn; } else { Point3m n=vcg::TriangleNormal(*fi); n.Normalize(); Point3m dir=CameraPos-vcg::Barycenter(*fi); dir.Normalize(); if(dir.dot(n) < minAngleCos) { (*fi).SetD(); --m.fn; } } } tri::Clean<CMeshO>::RemoveUnreferencedVertex(m); clock(); Matrix44m scaleMat; scaleMat.SetScale(scalingFactor,scalingFactor,scalingFactor); vcg::tri::UpdatePosition<CMeshO>::Matrix(m, scaleMat); return true; }
gpu::Texture* TextureUsage::create2DTextureFromImage(const QImage& srcImage, const std::string& srcImageName) { QImage image = srcImage; int imageArea = image.width() * image.height(); int opaquePixels = 0; int translucentPixels = 0; //bool isTransparent = false; int redTotal = 0, greenTotal = 0, blueTotal = 0, alphaTotal = 0; const int EIGHT_BIT_MAXIMUM = 255; QColor averageColor(EIGHT_BIT_MAXIMUM, EIGHT_BIT_MAXIMUM, EIGHT_BIT_MAXIMUM); if (!image.hasAlphaChannel()) { if (image.format() != QImage::Format_RGB888) { image = image.convertToFormat(QImage::Format_RGB888); } // int redTotal = 0, greenTotal = 0, blueTotal = 0; for (int y = 0; y < image.height(); y++) { for (int x = 0; x < image.width(); x++) { QRgb rgb = image.pixel(x, y); redTotal += qRed(rgb); greenTotal += qGreen(rgb); blueTotal += qBlue(rgb); } } if (imageArea > 0) { averageColor.setRgb(redTotal / imageArea, greenTotal / imageArea, blueTotal / imageArea); } } else { if (image.format() != QImage::Format_ARGB32) { image = image.convertToFormat(QImage::Format_ARGB32); } // check for translucency/false transparency // int opaquePixels = 0; // int translucentPixels = 0; // int redTotal = 0, greenTotal = 0, blueTotal = 0, alphaTotal = 0; for (int y = 0; y < image.height(); y++) { for (int x = 0; x < image.width(); x++) { QRgb rgb = image.pixel(x, y); redTotal += qRed(rgb); greenTotal += qGreen(rgb); blueTotal += qBlue(rgb); int alpha = qAlpha(rgb); alphaTotal += alpha; if (alpha == EIGHT_BIT_MAXIMUM) { opaquePixels++; } else if (alpha != 0) { translucentPixels++; } } } if (opaquePixels == imageArea) { qCDebug(modelLog) << "Image with alpha channel is completely opaque:" << QString(srcImageName.c_str()); image = image.convertToFormat(QImage::Format_RGB888); } averageColor = QColor(redTotal / imageArea, greenTotal / imageArea, blueTotal / imageArea, alphaTotal / imageArea); //isTransparent = (translucentPixels >= imageArea / 2); } gpu::Texture* theTexture = nullptr; if ((image.width() > 0) && (image.height() > 0)) { // bool isLinearRGB = true; //(_type == NORMAL_TEXTURE) || (_type == EMISSIVE_TEXTURE); bool isLinearRGB = false; //(_type == NORMAL_TEXTURE) || (_type == EMISSIVE_TEXTURE); gpu::Element formatGPU = gpu::Element(gpu::VEC3, gpu::NUINT8, (isLinearRGB ? gpu::RGB : gpu::SRGB)); gpu::Element formatMip = gpu::Element(gpu::VEC3, gpu::NUINT8, (isLinearRGB ? gpu::RGB : gpu::SRGB)); if (image.hasAlphaChannel()) { formatGPU = gpu::Element(gpu::VEC4, gpu::NUINT8, (isLinearRGB ? gpu::RGBA : gpu::SRGBA)); formatMip = gpu::Element(gpu::VEC4, gpu::NUINT8, (isLinearRGB ? gpu::BGRA : gpu::SBGRA)); } theTexture = (gpu::Texture::create2D(formatGPU, image.width(), image.height(), gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR))); theTexture->assignStoredMip(0, formatMip, image.byteCount(), image.constBits()); theTexture->autoGenerateMips(-1); } return theTexture; }