ZBLOG

class ImageProcessor { public: static QImage applyEdgeDetection(const QImage &input); static QImage applyThreshold(const QImage &input, int value); };

这是一个简单的图像处理类 ImageProcessor,提供了两个静态方法用于边缘检测和阈值处理。以下是完整的实现示例(基于Qt框架):

#include <QImage>
#include <QColor>
#include <vector>
#include <cmath>

class ImageProcessor {
public:
    // 使用Sobel算子进行边缘检测
    static QImage applyEdgeDetection(const QImage &input) {
        if(input.isNull()) return QImage();

        QImage result(input.size(), input.format());
        
        // Sobel算子核
        const int sobelX[3][3] = {{-1, 0, 1}, 
                                  {-2, 0, 2}, 
                                  {-1, 0, 1}};
        
        const int sobelY[3][3] = {{-1, -2, -1}, 
                                  {0,  0,  0}, 
                                  {1,  2,  1}};

        for(int y = 1; y < input.height()-1; y++) {
            for(int x = 1; x < input.width()-1; x++) {
                int pixelX = 0;
                int pixelY = 0;
                
                // 卷积计算
                for(int i = -1; i <= 1; i++) {
                    for(int j = -1; j <= 1; j++) {
                        QRgb rgb = input.pixel(x+j, y+i);
                        int gray = qGray(rgb);
                        
                        pixelX += gray * sobelX[i+1][j+1];
                        pixelY += gray * sobelY[i+1][j+1];
                    }
                }
                
                int magnitude = std::min(255, static_cast<int>(std::sqrt(pixelX*pixelX + pixelY*pixelY)));
                result.setPixel(x, y, qRgb(magnitude, magnitude, magnitude));
            }
        }
        
        return result;
    }

    // 阈值处理
    static QImage applyThreshold(const QImage &input, int threshold) {
        if(input.isNull()) return QImage();

        QImage result(input.size(), input.format());
        
        for(int y = 0; y < input.height(); y++) {
            for(int x = 0; x < input.width(); x++) {
                QRgb rgb = input.pixel(x,y);
                int gray = qGray(rgb);
                
                int newValue = (gray > threshold) ? 255 : 0;
                result.setPixel(x,y,qRgb(newValue, newValue, newValue));
            }
        }
        
        return result;
    }
};

使用说明:

// Qt中使用示例:
QImage original("image.jpg");
QImage edgeDetected = ImageProcessor::applyEdgeDetection(original);
QImage thresholded = ImageProcessor::applyThreshold(original,128);

//保存结果
edgeDetected.save("edges.jpg");
thresholded.save("threshold.jpg");

功能说明:

  • applyEdgeDetection: 使用Sobel算子检测图像边缘,返回灰度图形式的边缘检测结果

  • applyThreshold: 将图像二值化,大于阈值的像素设为白色(255),否则设为黑色(0)

注意:实际使用时需要包含Qt GUI模块,并在.pro文件中添加QT += gui


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23851

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?