Пример #1
0
QColor getDefaultIconColor(const QColor &color)
{
    QColor c = color;
    bool menuBackgrounIsLight = c.lightness() > lightThreshold;
    c.setHsl(c.hue(),
             qMax(0, qMin(255, c.saturation() + (menuBackgrounIsLight ? 30 : 10))),
             qMax(0, qMin(255, c.lightness() + (menuBackgrounIsLight ? -140 : 100))));

    return c;
}
Пример #2
0
bool isDarkTheme()
{
    QPalette pal = QApplication::palette();
    // QPalette::Base is used for the background of the Treeview
    QColor color = pal.color(QPalette::Active, QPalette::Base);
    return (color.lightness() < 127);
}
Пример #3
0
void OverlayAnimator::setActiveAppearance( bool active )
{
    QColor color = mEditor->palette().color(QPalette::Base);
    if(color.lightness() >= 128)
        color = color.darker(60);
    else
        color = color.lighter(50);
    
    if (active)
        color.setAlpha(0);
    else
        color.setAlpha(mEditor->inactiveFadeAlpha());

    mBackgroundAnimation.stop();

    if (mEditor->isVisible())
    {
        mBackgroundAnimation.setDuration(500);
        mBackgroundAnimation.setEasingCurve( QEasingCurve::OutCubic );
        mBackgroundAnimation.setStartValue( backgroundColor() );
        mBackgroundAnimation.setEndValue( color );
        mBackgroundAnimation.start();
    }
    else
    {
        setBackgroundColor(color);
    }
}
Пример #4
0
QImage edge_detector::double_thresholding(const QImage image)
{
    QImage destImage = QImage( image);
    QColor qc;

    int T1 = 16;
    int T2 = 12;

    int H = image.height();
    int W = image.width();

    for (int i=0; i<H; i++)
        for (int j=0; j<W; j++)
        {
            qc = ((QColor)image.pixel(j, i));
            int lightness = qc.lightness();
            int r = qc.red(), g = qc.green(), b = qc.blue();

            if (lightness > 200 || lightness < T2)
            {
                qc.setRgb(0, 0, 0);
            }
            else if (lightness > T1)
            {                
                qc.setRgb(255, 255, 255);
            }
            else
            {
                qc.setRgb(r?255:0, g?255:0, b?255:0);
            }
            destImage.setPixel( j, i, qc.rgba());
        }
    return destImage;
}
Пример #5
0
QPixmap ImageFilter::saturate(QImage origin, int delta)
{
    QImage newImage(origin.width(), origin.height(), QImage::Format_ARGB32);

    QColor oldColor;
    QColor newColor;
    int h,s,l;

    for(int x=0; x < newImage.width(); x++)
    {
        for(int y=0; y < newImage.height(); y++)
        {
            oldColor = QColor(origin.pixel(x, y));

            newColor = oldColor.toHsl();
            h = newColor.hue();
            s = newColor.saturation() + delta;
            l = newColor.lightness();

            //we check if the new value is between 0 and 255
            s = qBound(0, s, 255);

            newColor.setHsl(h, s, l);

            newImage.setPixel(x, y, qRgb(newColor.red(), newColor.green(), newColor.blue()));
        }
    }
    QPixmap processedImage(QPixmap::fromImage(newImage));

    return processedImage;
}
void Alg_DefaultEffects::applySaturation(QImage *image1, QImage *image2, int delta)
{
    QColor oldColor;
    QColor newColor;
    int h, s, l;

    for (int x = 0; x < image1->width(); x++)
    {
        for (int y = 0; y < image1->height(); y++)
        {
            oldColor = QColor(image1->pixel(x, y));

            newColor = oldColor.toHsl();
            h = newColor.hue();
            s = newColor.saturation()+delta;
            l = newColor.lightness();

            //we check if the new value is between 0 and 255
            s = qBound(0, s, 255);

            newColor.setHsl(h, s, l);

            image2->setPixel(x, y, qRgb(newColor.red(), newColor.green(), newColor.blue()));
        }
    }
}
Пример #7
0
LameImage ImageConverter::applyColorFilter(LameImage image)
{
    LameImage newimage(image.size(), LameImage::Format_Indexed8);
    newimage.setFrameSize(image.frameWidth(), image.frameHeight());
    newimage.setColorTable(_colors[_colorkey]);

    for (int y = 0; y < image.height(); y++)
    {
        for (int x = 0; x < image.width(); x++)
        {
            QColor color = image.pixel(x, y);
            int lightness = color.lightness();

            if (color == _transparent)
            {
                newimage.setPixel(x, y, 2);
            }
            else
            {
                if (lightness >= highbreak)
                    newimage.setPixel(x, y, 1);
                else if (lightness <= lowbreak)
                    newimage.setPixel(x, y, 0);
                else
                    newimage.setPixel(x, y, 3);
            }
        }
    }

    return newimage;
}
Пример #8
0
/// get strongest line in a quater, if there is no line
/// at all, an empty line (vote == 0) will be given
///
void Rotater::get_master_line(const QImage image, int quater, Form *line)
{
    QImage destImage = QImage( image);
    int h = m_height, w = m_width;

    // deal with 4 quaters of image accordingly
    int x_from, x_to, y_from, y_to;
    switch(quater)
    {
    case 1: x_from = 0, x_to = m_width/2, y_from = 0, y_to = m_height/2;
        break;
    case 2: x_from = m_width/2, x_to = w, y_from = 0, y_to = m_height/2;
        break;
    case 3: x_from = m_width/2, x_to = w, y_from = m_height/2, y_to = h;
        break;
    case 4: x_from = 0, x_to = m_width/2, y_from = m_height/2, y_to = h;
        break;
    }

    // voting lines in area of the quater
    QColor qc;
    m_line_detector->reset();
    for (int i=y_from; i<y_to; i++)
    {
        for (int j=x_from; j<x_to; j++)
        {
            qc = (QColor)destImage.pixel(j, i);
            if (qc.lightness() > 200)
                m_line_detector->vote(j, i);
        }
    }
    vector<Form> lines = m_line_detector->get_lines();
    int prefered_group = m_sign * ((quater == 1 || quater == 3) ? 1 : -1);

    // get the line that has hightest voting in the quater
    qreal alpha, min_alpha = 10;
    bool alphaOk = false, lineEndOk = false;
    int x0, y0, x1, y1;
    for (int i=0; i<(int)lines.size(); i++)
    {
        if (lines.at(i).vote <= line->vote) continue;

        m_line_detector->get_line_ends_and_alpha(lines.at(i), &x0, &y0, &x1, &y1, &alpha);
        alphaOk = (prefered_group == 1 && fabs(alpha) < 90 - min_alpha) ||
                  (prefered_group == -1 && fabs(alpha) > min_alpha && fabs(alpha) < 180 - min_alpha);
        lineEndOk = (quater == 4 && m_sign > 0 && (y0 == m_height || y1 == m_height)) ||
                    (quater == 4 && m_sign < 0 && (x0 == 0 || x1 == 0)) ||
                    (quater == 3 && m_sign > 0 && (x0 == m_width || x1 == m_width)) ||
                    (quater == 3 && m_sign < 0 && (y0 == m_height || y1 == m_height)) ||
                    (quater == 2 && m_sign > 0 && (y0 == 0 || y1 == 0)) ||
                    (quater == 2 && m_sign < 0 && (x0 == m_width || x1 == m_width)) ||
                    (quater == 1 && m_sign > 0 && (x0 == 0 || x1 == 0)) ||
                    (quater == 1 && m_sign < 0 && (y0 == 0 || y1 == 0));

        if (alphaOk && lineEndOk) *line = lines.at(i);
    }
}
Пример #9
0
void LoadWindow::on_colorButton_clicked()
{
    QColor c = QColorDialog::getColor(holder.profile().color());

    if (!c.isValid() || (c.isValid() && (c.lightness() > 140 || c.green() > 180))) { // So they can click cancel without their colour disappearing!
        return;
    }

    holder.profile().color() = c;
    setColor(c);
}
Пример #10
0
void TrainerMenu::on_colorButton_clicked()
{
    QColor c = QColorDialog::getColor(team().color());

    if (c.isValid() && (c.lightness() > 140 || c.green() > 180)) {
        return;
    }

    team().color() = c;
    setColor();
}
Пример #11
0
void ContinuousColorRange::add(const QVariant &v)
{
    if ( contains(v))
        return;
    QColor clr = toColor(v, defaultColorModel());
    if ( !clr.isValid())
        return;
    if ( defaultColorModel() == ColorRangeBase::cmRGBA){
        _limit1.setRed(std::min(_limit1.red(), clr.red()));
        _limit1.setGreen(std::min(_limit1.green(), clr.green()));
        _limit1.setBlue(std::min(_limit1.blue(), clr.blue()));
        _limit1.setAlpha(std::min(_limit1.alpha(), clr.alpha()));
        _limit2.setRed(std::max(_limit2.red(), clr.red()));
        _limit2.setGreen(std::max(_limit2.green(), clr.green()));
        _limit2.setBlue(std::max(_limit2.blue(), clr.blue()));
        _limit2.setAlpha(std::max(_limit2.alpha(), clr.alpha()));
    }else if (defaultColorModel() == ColorRangeBase::cmHSLA) {
        _limit1.setHsl(std::min(_limit1.hue(), clr.hue()),
                       std::min(_limit1.saturation(), clr.saturation()),
                       std::min(_limit1.lightness(), clr.lightness()));
        _limit1.setAlpha(std::min(_limit1.alpha(), clr.alpha()));
        _limit2.setHsl(std::max(_limit2.hue(), clr.hue()),
                       std::max(_limit2.saturation(), clr.saturation()),
                       std::max(_limit2.lightness(), clr.lightness()));
        _limit2.setAlpha(std::max(_limit2.alpha(), clr.alpha()));
    }
    else if ( defaultColorModel() == ColorRangeBase::cmCYMKA){
        _limit1.setCmyk(std::min(_limit1.cyan(), clr.cyan()),
                        std::min(_limit1.magenta(), clr.magenta()),
                        std::min(_limit1.yellow(), clr.yellow()),
                        std::min(_limit1.black(), clr.black()));
        _limit1.setAlpha(std::min(_limit1.alpha(), clr.alpha()));
        _limit2.setCmyk(std::max(_limit2.cyan(), clr.cyan()),
                        std::max(_limit2.magenta(), clr.magenta()),
                        std::max(_limit2.yellow(), clr.yellow()),
                        std::max(_limit2.black(), clr.black()));
        _limit2.setAlpha(std::max(_limit2.alpha(), clr.alpha()));

    }

}
Пример #12
0
PlatformStyle::PlatformStyle(const QString& name, bool imagesOnButtons, bool colorizeIcons, bool useExtraSpacing) : name(name),
                                                                                                                    imagesOnButtons(imagesOnButtons),
                                                                                                                    colorizeIcons(colorizeIcons),
                                                                                                                    useExtraSpacing(useExtraSpacing),
                                                                                                                    singleColor(0, 0, 0),
                                                                                                                    textColor(0, 0, 0)
{
    // Determine icon highlighting color
    if (colorizeIcons) {
        const QColor colorHighlightBg(QApplication::palette().color(QPalette::Highlight));
        const QColor colorHighlightFg(QApplication::palette().color(QPalette::HighlightedText));
        const QColor colorText(QApplication::palette().color(QPalette::WindowText));
        const int colorTextLightness = colorText.lightness();
        QColor colorbase;
        if (abs(colorHighlightBg.lightness() - colorTextLightness) < abs(colorHighlightFg.lightness() - colorTextLightness))
            colorbase = colorHighlightBg;
        else
            colorbase = colorHighlightFg;
        singleColor = colorbase;
    }
    // Determine text color
    textColor = QColor(QApplication::palette().color(QPalette::WindowText));
}
Пример #13
0
bool MainWindow::eventFilter(QObject *obj, QEvent *ev)
{
    if(!currentImageSteps->at(*currentStep))
        return false;
    if(obj == currentImageLabel && ev->type() == QEvent::MouseMove)
    {
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(ev);
        QPoint pnt = currentImageLabel->mapFromGlobal(mouseEvent->globalPos());
        QColor currentPixel = currentImageSteps->at(*currentStep)->pixel(pnt);
        statusBar()->showMessage(QString("%1@(%2,%3)").arg(currentPixel.lightness()&0xFF).arg(pnt.x()).arg(pnt.y()));
        currentRubberBand->setGeometry(QRect(rbOrigin,pnt).normalized());
        return true;
    }
    if(obj == currentImageLabel && ev->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(ev);
        rbOrigin = currentImageLabel->mapFromGlobal(mouseEvent->globalPos());
        currentRubberBand->setGeometry(QRect(rbOrigin,QSize()));
        currentRubberBand->show();
    }
    if(obj == currentImageLabel && ev->type() == QEvent::MouseButtonRelease)
    {
        currentRubberBand->hide();

        *currentImageSteps << new QImage(currentImageSteps->at(*currentStep)->copy(currentRubberBand->geometry()));
        *currentStep = currentImageSteps->size()-2;
        nextImage();
        /*
        SparseMatrix* sm = buildModel(img);

        QDialog* dlg = new QDialog(this);
        QHBoxLayout* mainLayout = new QHBoxLayout(dlg);

        QTextEdit *edit = new QTextEdit(this);
        edit->setReadOnly(true);
        edit->setText(sm->toString());
        edit->resize(800,600);

        mainLayout->addWidget(edit);
        dlg->setLayout(mainLayout);
        dlg->setAttribute(Qt::WA_DeleteOnClose);
        dlg->resize(800,600);
        dlg->show();
        delete sm;
        */
    }
    return false;
}
Пример #14
0
void ColorEditor::setColor(const QColor &c) {
  this->c = c;
  button->setText(QString("R/G/B/A: %1/%2/%3/%4")
    .arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha()));

  // Change colors of the button to make it nicer
  QColor textColor;
  if (c.lightness() > 164) {
    textColor = "#000000";
  } else {
    textColor = "#FFFFFF";
  }
  QString style = QString("background-color: ") + c.name() +
    "; color: " + textColor.name() + ";";
  button->setStyleSheet(style);
}
Пример #15
0
void ColorRangeBase::storeColor(const QColor& clr, QDataStream &stream)
{
    switch (defaultColorModel()){
    case ColorRangeBase::cmRGBA:
        stream << clr.red() << clr.green() << clr.blue() << clr.alpha();
        break;
    case ColorRangeBase::cmHSLA:
        stream << clr.hue() << clr.saturation() << clr.lightness() << clr.alpha();
        break;
    case ColorRangeBase::cmCYMKA:
        stream << clr.yellow() << clr.magenta() << clr.cyan() << clr.black();
        break;
    case ColorRangeBase::cmGREYSCALE:
        stream << clr.red();
    default:
        break;
    }
}
Пример #16
0
void TrainerMenu::on_colorButton_clicked()
{
    QColor c = QColorDialog::getColor(team().color());

    if (c.green() + c.red() + c.blue() == 0) {
        c.setBlue(1);
    }

    if (!c.isValid())
        return;

    int luma = (c.green()*3 + c.blue() +c.red()*2)/6;
    if ((luma > 140 && c.lightness() > 140) || c.green() > 200) { // So they can click cancel without their colour disappearing!
        QMessageBox::information(NULL, tr("Invalid Color"), tr("Your color must have less than 200 parts green, brightness less than 140, and lightness less than 140.\n\nYour selected color currently has %1 parts green, a brightness of %2, and a lightness of %3.").arg(c.green()).arg(luma).arg(c.lightness()));
        return;
    }

    team().color() = c;
    setColor();
}
Пример #17
0
 void drawPrimitive(PrimitiveElement element, const QStyleOption * option, QPainter * painter, const QWidget * widget = 0) const {
     const QStyleOptionViewItem *vopt = NULL;
     switch (element) {
         case PE_PanelItemViewItem:
             // Highlight the current, selected item with a different background in an item view if the highlight current item property is set
             if (option->state & QStyle::State_HasFocus && (vopt = qstyleoption_cast<const QStyleOptionViewItem *>(option)) && widget && widget->property("highlight_current_item").toBool()) {
                 QColor color = vopt->palette.color(QPalette::Normal, QPalette::Highlight);
                 QStyleOptionViewItem opt = QStyleOptionViewItem(*vopt);
                 if (color.lightness() > 128)
                     color = color.darker(widget->property("highlight_current_item").toInt());
                 else
                     color = color.lighter(125);
                 opt.palette.setColor(QPalette::Highlight, color);
                 return QProxyStyle::drawPrimitive(element, &opt, painter, widget);
             }
             break;
         default:
             break;
     }
     return QProxyStyle::drawPrimitive(element, option, painter, widget);
 }
Пример #18
0
/*
 *  Method that read the image and create two dimensional array of colors from this image
 *
 *  @param  filePath Path to image file
 *  @param  imageMatrix 2d array that contains color's
 *  @param  width The width of the image
 *  @param  height The height of the image
 */
void SilCounter::createImageMatrixOfColour(string& filePath, int** &imageMatrix, int &width, int &height){
    // creating QImage from image that was set by user
    QImage* image = new QImage(&filePath[0]);

    // geting width and height from image
    width = (*image).width();
    height = (*image).height();


    // creating 2d array that will store color of image pixels
    imageMatrix = new int*[height];
    for(int i = 0; i < height; i++){
        imageMatrix[i] = new int [width];
    }

    // cheking if this image is a PNG file
    bool png = false;
    string pngCheck = filePath.substr(filePath.length() - 3,filePath.length());
    if(pngCheck == "png" || pngCheck == "PNG"){
        png = true;
    }

    // geting alpha component if it is a PNG, or lightness, from each pixel of the image
    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            if(png){
                QRgb tempColor = (*image).pixel(j,i);
                int alpha = qAlpha(tempColor);
                imageMatrix[i][j] = alpha;
            }else{
                QColor tempColor  = (*image).pixel(j,i);
                int alpha = tempColor.lightness();
                imageMatrix[i][j] = alpha;
            }
        }
    }
    delete image;
}
Пример #19
0
bool LIFXLightClient::sendColour()
{
    LIFXPacket *packet = new LIFXPacket(LIFX_SET_LIGHT_COLOR);
    memcpy(packet->header.target_mac_address, m_addressraw, sizeof(packet->header.target_mac_address));
    LIFXSetLightColorPayload *payload = (LIFXSetLightColorPayload*)packet->payloaddata;
    if(payload != NULL)
    {
        QColor color = QColor::fromRgb(red, green, blue);
        //color.getHsl( *payload->hue, *payload->saturation, *payload->brightness);

        payload->stream     = 0;
        payload->hue        = color.hslHue() *275;
        payload->saturation = color.hslSaturation()*257;
        payload->brightness = color.lightness()*655.35;
        payload->kelvin     = kelvin;
        payload->fade_time  = fadetime;

        ((LIFXGatewayClient*)gatewayclient)->SendPacket(packet);
        return true;
    }

    return false;
}
Пример #20
0
void MainWindow::load()
{
    ui->fitnessButton->setEnabled(false);
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::currentPath());
    if (!fileName.isEmpty()) {
        resetImageStack();
        *currentImageSteps << new QImage(fileName);
        if (currentImageSteps->first()->isNull())
        {
            QMessageBox::information(this, tr("FRC 2010 Vision"), tr("Cannot load %1.").arg(fileName));
            return;
        }
        for(int y = 0; y < currentImageSteps->first()->height(); y++) {
            for(int x = 0; x < currentImageSteps->first()->width(); x++) {
                QColor pixel = currentImageSteps->first()->pixel(x, y);
                int gray = pixel.lightness();
                currentImageSteps->first()->setPixel(x, y, qRgb(gray, gray, gray));
            }
        }
        currentImageLabel->setPixmap(QPixmap::fromImage(*(currentImageSteps->at(*currentStep))));
    }
    updatePageNumbers();
}
Пример #21
0
QList<int> AdaptAver::vicinity(QImage *picture, int power, int curx, int cury, int chanel)
{ //функция возвращает окрестность заданного пикселя
    QList<int> proxArray;
    for (int y = cury - power; y <= cury+ power; y++)
        for (int x = curx - power; x <= curx+ power; x++)
        { //проверяем окрестные пиксели
            if ((0 <= x && x <= picture->width()-1) && (0 <= y && y <= picture->height()-1))
            { //запоминаем их цвета
                QColor pixel = picture->pixel(x, y);
                if (chanel == 1)
                    proxArray.append(pixel.red());
                if (chanel == 2)
                    proxArray.append(pixel.green());
                if (chanel == 3)
                    proxArray.append(pixel.blue());
                if (chanel ==4)
                    proxArray.append(pixel.lightness());
            }
            else { //если мы за пределами изображения, то запоминаем чёрный цвет
                proxArray.append(0);
            }
        }
    return proxArray;
}
Пример #22
0
void FlatButton::setIcons(const QIcon& _icon, const QIcon& _checkedIcon, const QIcon& _hoverIcon)
{
	m_icon = _icon;
	ImageHelper::setIconColor(m_icon, ICON_SIZE, palette().text().color());

	m_checkedIcon = _checkedIcon;
	if (!m_checkedIcon.isNull()) {
		m_checkedIconHighlight = false;
		ImageHelper::setIconColor(m_checkedIcon, ICON_SIZE, palette().text().color());
	} else {
		m_checkedIconHighlight = true;
		m_checkedIcon = _icon;
		QColor highlightColor = palette().highlight().color();
#ifdef Q_OS_MAC
		highlightColor.setHsl(highlightColor.hslHue(), highlightColor.hslSaturation(),
			highlightColor.lightness() - 50);
#endif
		ImageHelper::setIconColor(m_checkedIcon, ICON_SIZE, highlightColor);
	}

	m_hoverIcon = _hoverIcon;

	aboutUpdateIcon();
}
Пример #23
0
QColor ViewItem::select_text_colour(QColor background)
{
	return (background.lightness() > 110) ? Qt::black : Qt::white;
}
Пример #24
0
void GenericCodeEditor::paintLineIndicator( QPaintEvent *e )
{
    QPalette plt( mLineIndicator->palette() );
    QRect r( e->rect() );
    QPainter p( mLineIndicator );

    p.fillRect( r, plt.color( QPalette::Mid ) );

    QTextDocument *doc = QPlainTextEdit::document();
    QTextCursor cursor(textCursor());
    int selStartBlock, selEndBlock;
    if (cursor.hasSelection()) {
        selStartBlock = doc->findBlock(cursor.selectionStart()).blockNumber();
        selEndBlock = doc->findBlock(cursor.selectionEnd()).blockNumber();
    }
    else
        selStartBlock = selEndBlock = -1;

    QTextBlock block = firstVisibleBlock();
    int blockNumber = block.blockNumber();
    qreal top = blockBoundingGeometry(block).translated(contentOffset()).top();
    qreal bottom = top + blockBoundingRect(block).height();

    while (block.isValid() && top <= e->rect().bottom()) {
        if (block.isVisible() && bottom >= e->rect().top()) {
            p.save();

            QRectF numRect( 0, top, mLineIndicator->width() - 1, bottom - top );

            int num = blockNumber;
            if (num >= selStartBlock && num <= selEndBlock) {
                num -= selStartBlock;
                p.setPen(Qt::NoPen);
                p.setBrush(plt.color(QPalette::Highlight));
                p.drawRect(numRect);
                p.setPen(plt.color(QPalette::HighlightedText));
            }

            QString number = QString::number(num + 1);
            p.setPen(plt.color(QPalette::ButtonText));
            p.drawText(0, top, mLineIndicator->width() - 10, bottom - top,
                       Qt::AlignRight, number);

            p.restore();
        }

        block = block.next();
        top = bottom;
        bottom = top + blockBoundingRect(block).height();
        ++blockNumber;
    }
    
    if(!mEditorBoxIsActive) {
        QColor color = plt.color(QPalette::Mid);
        if(color.lightness() >= 128)
            color = color.darker(60);
        else
            color = color.lighter(50);
        
        color.setAlpha(inactiveFadeAlpha());
        p.fillRect( r, color );
    }
}
Пример #25
0
// Hàm dùng lọc ảnh bằng các filter tương ứng
QImage ExtraFiltersPlugin::filterImage(const QString &filter,
                                       const QImage &image, QWidget *parent) {
    // Chuyển đổi định dạng ảnh sang RGB 32-bit để các hàm làm việc như mong
    // đợi
    QImage original = image.convertToFormat(QImage::Format_RGB32);
    QImage result = original;

    if (filter == tr("Lật ngang")) {
        // Nếu filter là "Lật ngang" thì hoán đổi các pixel của ảnh theo chiều
        // ngang của ảnh
        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("Lật dọc")) {
        // Nếu filter là "Lật dọc" thì hoán đổi các pixel của ảnh theo chiều
        // dọc của ảnh
        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("Làm mờ")) {
        // Ta sẽ nhân từng điểm ảnh với ma trận tích chập để làm mờ
        // trừ các điểm ở biên.
        int kernel[5][5] = {{0, 0, 1, 0, 0},
            {0, 1, 3, 1, 0},
            {1, 3, 7, 3, 1},
            {0, 1, 3, 1, 0},
            {0, 0, 1, 0, 0}
        };
        int kernelSize = 5;
        int sumKernel = 27;
        int r, g, b;
        int pixel;

        for (int x = kernelSize / 2; x < original.width() - (kernelSize / 2); ++x) {
            for (int y = kernelSize / 2; y < original.height() - (kernelSize / 2); ++y) {
                r = 0;
                g = 0;
                b = 0;
                // Tính tổng giá trị màu của điểm pixel và các điểm ảnh xung quanh
                for ( int i =  -kernelSize / 2 ; i <= kernelSize / 2 ; ++i) {
                    for ( int j =  -kernelSize / 2 ; j <= kernelSize / 2 ; ++j) {
                        pixel = original.pixel ( x + i , y + j );
                        r += qRed(pixel) * kernel[kernelSize / 2 + i][kernelSize / 2 + j] ;
                        g += qGreen(pixel) * kernel[kernelSize / 2 + i][kernelSize / 2 + j];
                        b += qBlue(pixel) * kernel[kernelSize / 2 + i][kernelSize / 2 + j];
                    }
                }

                // Kiểm tra giá trị các màu trong khoảng giới hạn
                r = qBound ( 0 , r / sumKernel ,  255 );
                g = qBound ( 0 , g / sumKernel ,  255 );
                b = qBound ( 0 , b / sumKernel ,  255 );

                result.setPixel ( x, y, qRgba(r , g , b, qAlpha(pixel)));
            }
        }

    } else if (filter == tr("Ảnh nhị phân")) {
        // Nếu filter là "Ảnh nhị phân" thì bật QInputDialog lên cho người dùng
        // nhập vào giá trị ngưỡng, nằm trong khoảng 0 đến 255
        bool ok; // Kiểm tra giá trị nhập
        int threshold = QInputDialog::getInt(parent, tr("Ảnh nhị phân"),
                                             tr("Nhập ngưỡng:"),
                                             85, 0, 255, 1, &ok);
        // Đầu tiên ta chuyển ảnh về ảnh đa mức xám rồi so sánh từng pixel của
        // ảnh với giá trị ngưỡng.
        if (ok) {
            for (int y = 0; y < original.height(); ++y) {
                for (int x = 0; x < original.width(); ++x) {
                    int pixel = original.pixel(x, y);
                    int gray = qGray(pixel);
                    gray = gray > threshold ? 255 : 0;
                    pixel = qRgb(gray, gray, gray);
                    result.setPixel(x, y, pixel);
                }
            }
        }
    } else if (filter == tr("Ảnh âm bản")) {
        // Dùng hàm invertPixels() để đảo ngược các pixel.
        result.invertPixels();
    } else if (filter == tr("Đảo màu (RGB->BGR)")) {
        // Dùng hàm rgbSwapped() để chuyển kênh màu của ảnh từ RGB sang BGR
        result = result.rgbSwapped();
    } else if (filter == tr("Đa mức xám")) {
        //
        for (int y = 0; y < result.height(); ++y) {
            for (int x = 0; x < result.width(); ++x) {
                int pixel = result.pixel(x, y);
                int gray = qGray(pixel);
                int alpha = qAlpha(pixel);
                result.setPixel(x, y, qRgba(gray, gray, gray, alpha));
            }
        }
    } else if (filter == tr("Độ sáng")) {
        // Nếu filter là "Độ sáng" thì bật QInputDialog lên cho người dùng
        // nhập vào giá trị ngưỡng, giá trị này trong khoảng -255 đến 255
        bool ok;  // Kiểm tra giá trị nhập
        int brighness = QInputDialog::getInt(parent, tr("Độ sáng"),
                                             tr("Nhập độ sáng:"),
                                             10, -255, 255, 1, &ok);
        // Ta tăng hoặc giảm giá trị các màu của từng pixel
        if (ok) {
            int r, g, b;

            for (int x = 0; x < original.width(); x++) {
                for (int y = 0; y < original.height(); y++) {

                    int pixel = original.pixel(x, y);

                    r = qRed(pixel) + brighness;
                    g = qGreen(pixel) + brighness;
                    b = qBlue(pixel) + brighness;

                    //Ta kiểm tra các giá trị mới trong khoảng cho phép.
                    r = qBound(0, r, 255);
                    g = qBound(0, g, 255);
                    b = qBound(0, b, 255);

                    result.setPixel(x, y, qRgba(r, g, b, qAlpha(pixel)));
                }
            }
        }
    } else if (filter == tr("Làm ấm")) {
        // Nếu filter là "Làm ấm" thì bật QInputDialog lên cho người dùng
        // nhập vào giá trị, giá trị này trong khoảng 1 đến 255
        bool ok;  // Kiểm tra giá trị nhập
        int delta = QInputDialog::getInt(parent, tr("Lầm ấm"),
                                         tr("Nhập mức độ ấm:"),
                                         10, 1, 255, 1, &ok);
        // Hình sẽ trong ấm hơn nếu ta tăng độ vàng của ảnh, và màu vàng được
        // tổng hợp từ màu đỏ và xanh lục trong kênh màu RGB
        if (ok) {
            int r, g, b;

            for (int x = 0; x < original.width(); x++) {
                for (int y = 0; y < original.height(); y++) {

                    int pixel = original.pixel(x, y);

                    r = qRed(pixel) + delta;
                    g = qGreen(pixel) + delta;
                    b = qBlue(pixel);

                    //Ta kiểm tra các giá trị mới trong khoảng cho phép.
                    r = qBound(0, r, 255);
                    g = qBound(0, g, 255);

                    result.setPixel(x, y, qRgba(r, g, b, qAlpha(pixel)));
                }
            }
        }
    } else if (filter == tr("Làm mát...")) {
        // Nếu filter là "Làm mát" thì bật QInputDialog lên cho người dùng
        // nhập vào giá trị, giá trị này trong khoảng 1 đến 255
        bool ok;  // Kiểm tra giá trị nhập
        int delta = QInputDialog::getInt(parent, tr("Lầm mát"),
                                         tr("Nhập mức độ mát:"),
                                         10, 1, 256, 1, &ok);
        // Hình sẽ có cảm giác mát hơn khi ta tăng giá trị kênh màu xanh lam
        if (ok) {
            int r, g, b;

            for (int x = 0; x < original.width(); x++) {
                for (int y = 0; y < original.height(); y++) {

                    int pixel = original.pixel(x, y);

                    r = qRed(pixel);
                    g = qGreen(pixel);
                    b = qBlue(pixel) + delta;

                    //Ta kiểm tra giá trị mới trong khoảng cho phép.
                    b = qBound(0, b, 255);

                    result.setPixel(x, y, qRgba(r, g, b, qAlpha(pixel)));
                }
            }
        }
    } else if (filter == tr("Độ bão hòa")) {
        // Nếu filter là "Độ bão hòa" thì bật QInputDialog lên cho người dùng
        // nhập vào giá trị, giá trị này trong khoảng -255 đến 255
        bool ok; // Kiểm tra giá trị nhập vào
        int delta = QInputDialog::getInt(parent, tr("Độ bão hòa"),
                                         tr("Nhập độ bão hòa:"),
                                         10, -255, 255, 1, &ok);
        QColor newClolor;
        QColor oldColor;
        int h, s, l;

        // Ta chuyển hình về kênh màu HSL rồi sau đó tăng hoặc giảm kênh
        // saturation để tăng hoặc giảm độ bão hòa sau đó lại chuyển ảnh về RGB
        if (ok) {
            for (int y = 0; y < original.height(); ++y) {
                for (int x = 0; x < original.width(); ++x) {

                    oldColor = QColor(original.pixel(x, y));
                    newClolor = oldColor.toHsl();

                    h = newClolor.hue();
                    s = newClolor.saturation() + delta;
                    l = newClolor.lightness();

                    // Ta kiểm tra giá trị mới trong khoảng cho phép
                    s = qBound(0, s, 255);

                    newClolor.setHsl(h, s, l);

                    result.setPixel(x, y, qRgba(newClolor.red(),
                                                newClolor.green(),
                                                newClolor.blue(),
                                                newClolor.alpha()));
                }
            }
        }
    }
    return result;
}
Пример #26
0
/* 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;
}
Пример #27
0
SeekSlider::SeekSlider( Qt::Orientation q, QWidget *_parent, bool _static )
          : QSlider( q, _parent ), b_classic( _static )
{
    isSliding = false;
    f_buffering = 1.0;
    mHandleOpacity = 1.0;
    chapters = NULL;
    mHandleLength = -1;

    // prepare some static colors
    QPalette p = palette();
    QColor background = p.color( QPalette::Active, QPalette::Background );
    tickpointForeground = p.color( QPalette::Active, QPalette::WindowText );
    tickpointForeground.setHsv( tickpointForeground.hue(),
            ( background.saturation() + tickpointForeground.saturation() ) / 2,
            ( background.value() + tickpointForeground.value() ) / 2 );

    // set the background color and gradient
    QColor backgroundBase( p.window().color() );
    backgroundGradient.setColorAt( 0.0, backgroundBase.darker( 140 ) );
    backgroundGradient.setColorAt( 1.0, backgroundBase );

    // set the foreground color and gradient
    QColor foregroundBase( 50, 156, 255 );
    foregroundGradient.setColorAt( 0.0,  foregroundBase );
    foregroundGradient.setColorAt( 1.0,  foregroundBase.darker( 140 ) );

    // prepare the handle's gradient
    handleGradient.setColorAt( 0.0, p.window().color().lighter( 120 ) );
    handleGradient.setColorAt( 0.9, p.window().color().darker( 120 ) );

    // prepare the handle's shadow gradient
    QColor shadowBase = p.shadow().color();
    if( shadowBase.lightness() > 100 )
        shadowBase = QColor( 60, 60, 60 ); // Palette's shadow is too bright
    shadowDark = shadowBase.darker( 150 );
    shadowLight = shadowBase.lighter( 180 );
    shadowLight.setAlpha( 50 );

    /* Timer used to fire intermediate updatePos() when sliding */
    seekLimitTimer = new QTimer( this );
    seekLimitTimer->setSingleShot( true );

    /* Tooltip bubble */
    mTimeTooltip = new TimeTooltip( this );
    mTimeTooltip->setMouseTracking( true );

    /* Properties */
    setRange( MINIMUM, MAXIMUM );
    setSingleStep( 2 );
    setPageStep( 10 );
    setMouseTracking( true );
    setTracking( true );
    setFocusPolicy( Qt::NoFocus );

    /* Use the new/classic style */
    if( !b_classic )
        setStyle( new SeekStyle );

    /* Init to 0 */
    setPosition( -1.0, 0, 0 );
    secstotimestr( psz_length, 0 );

    animHandle = new QPropertyAnimation( this, "handleOpacity", this );
    animHandle->setDuration( FADEDURATION );
    animHandle->setStartValue( 0.0 );
    animHandle->setEndValue( 1.0 );

    hideHandleTimer = new QTimer( this );
    hideHandleTimer->setSingleShot( true );
    hideHandleTimer->setInterval( FADEOUTDELAY );

    CONNECT( this, sliderMoved( int ), this, startSeekTimer() );
    CONNECT( seekLimitTimer, timeout(), this, updatePos() );
    CONNECT( hideHandleTimer, timeout(), this, hideHandle() );
    mTimeTooltip->installEventFilter( this );
}
Пример #28
0
void tst_QColor::setHsl()
{
    QColor color;

    for (int A = 0; A <= USHRT_MAX; ++A) {
        {
            // 0-255
            int a = A >> 8;
            color.setHsl(0, 0, 0, a);
            QCOMPARE(color.alpha(), a);

            int h, s, l, a2;
            color.getHsv(&h, &s, &l, &a2);
            QCOMPARE(a2, a);
        }

        {
            // 0.0-1.0
            qreal a = A / qreal(USHRT_MAX);
            color.setHslF(0.0, 0.0, 0.0, a);
            QCOMPARE(color.alphaF(), a);

            qreal h, s, l, a2;
            color.getHslF(&h, &s, &l, &a2);
            QCOMPARE(a2, a);
        }
    }

    for (int H = 0; H < 36000; ++H) {
        {
            // 0-255
            int h = H / 100;

            color.setHsl(h, 0, 0, 0);
            QCOMPARE(color.hslHue(), h);

            int h2, s, l, a;
            color.getHsl(&h2, &s, &l, &a);
            QCOMPARE(h2, h);
        }

        {
            // 0.0-1.0
            qreal h = H / 36000.0;
            color.setHslF(h, 0.0, 0.0, 0.0);
            QCOMPARE(color.hslHueF(), h);

            qreal h2, s, l, a;
            color.getHslF(&h2, &s, &l, &a);
            QCOMPARE(h2, h);
        }
    }

    for (int S = 0; S <= USHRT_MAX; ++S) {
        {
            // 0-255
            int s = S >> 8;
            color.setHsl(0, s, 0, 0);
            QCOMPARE(color.hslSaturation(), s);

            int h, s2, l, a;
            color.getHsl(&h, &s2, &l, &a);
            QCOMPARE(s2, s);
        }

        {
            // 0.0-1.0
            qreal s = S / qreal(USHRT_MAX);
            color.setHslF(0.0, s, 0.0, 0.0);
            QCOMPARE(color.hslSaturationF(), s);

            qreal h, s2, l, a;
            color.getHslF(&h, &s2, &l, &a);
            QCOMPARE(s2, s);
        }
    }

    for (int L = 0; L <= USHRT_MAX; ++L) {
        {
            // 0-255
            int l = L >> 8;
            color.setHsl(0, 0, l, 0);
            QCOMPARE(color.lightness(),  l);

            int h, s, l2, a;
            color.getHsl(&h, &s, &l2, &a);
            QCOMPARE(l2, l);
        }

        {
            // 0.0-1.0
            qreal l = L / qreal(USHRT_MAX);
            color.setHslF(0.0, 0.0, l, 0.0);
            QCOMPARE(color.lightnessF(), l);

            qreal h, s, l2, a;
            color.getHslF(&h, &s, &l2, &a);
            QCOMPARE(l2, l);
        }
    }
}