Compare commits

..
6 Commits
Author SHA1 Message Date
luochen570 804a5db77d Update Windows build documentation 2026-05-31 12:48:56 +08:00
luochen570 4e1f73bab7 deleted: QtOpenCVImageTool.zip
deleted:    build_windows.bat
	deleted:    build_wsl_windows.sh
	deleted:    cmake/toolchains/mingw64.cmake
2026-05-31 12:41:15 +08:00
luochen570 57c053c77a Add WSL Windows cross build script 2026-05-31 12:27:14 +08:00
luochen570 4102ff3b74 Add Windows build helper 2026-05-31 12:20:24 +08:00
luochen570 7e7c9f1d74 Document Windows build setup 2026-05-31 12:14:45 +08:00
luochen570 c658fa4265 Initial Qt OpenCV image tool 2026-05-31 12:10:10 +08:00
11 changed files with 701 additions and 914 deletions
-205
View File
@@ -1,205 +0,0 @@
name: Build Windows Release
on:
push:
branches:
- main
tags:
- 'v*'
workflow_dispatch:
permissions:
contents: write
jobs:
build-windows-release:
name: Build Windows x64 Release on Linux (MinGW + Qt + OpenCV)
runs-on: ubuntu-latest
container: fedora:latest
env:
BUILD_TYPE: Release
PACKAGE_BASENAME: chengnan-windows-x64-mingw
steps:
- name: Configure Fedora TUNA mirror
run: |
set -euo pipefail
sed -e 's|^metalink=|#metalink=|g' \
-e 's|^#baseurl=http://download.example/pub/fedora/linux|baseurl=https://mirrors.aliyun.com/fedora|g' \
-i /etc/yum.repos.d/fedora*.repo
if [ -f /etc/yum.repos.d/fedora-cisco-openh264.repo ]; then
sed -i 's|^enabled=1|enabled=0|g' /etc/yum.repos.d/fedora-cisco-openh264.repo
fi
dnf clean all
dnf makecache --refresh -y
- name: Install cross build dependencies
run: |
set -euo pipefail
dnf install -y \
git \
curl \
jq \
zip \
unzip \
python3 \
nodejs \
cmake \
ninja-build \
mingw64-gcc-c++ \
mingw64-qt6-qtbase \
mingw64-qt6-qtimageformats \
mingw64-opencv
- name: Checkout
uses: actions/checkout@v4
- name: Configure cross build
run: |
cmake -S . -B build-windows -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-mingw64.cmake \
-DCMAKE_BUILD_TYPE="$BUILD_TYPE" \
-DCMAKE_CXX_FLAGS="-isystem /usr/x86_64-w64-mingw32/sys-root/mingw/include/opencv4" \
-DOpenCV_DIR=/usr/x86_64-w64-mingw32/sys-root/mingw/lib/cmake/OpenCV
- name: Build
run: cmake --build build-windows --config "$BUILD_TYPE" --parallel
- name: Package Windows app
run: |
set -euo pipefail
root="/usr/x86_64-w64-mingw32/sys-root/mingw"
dist="dist-windows/chengnan"
rm -rf "$dist" artifacts
mkdir -p "$dist/platforms" "$dist/imageformats" artifacts
cp build-windows/chengnan.exe "$dist/"
cp "$root/bin/Qt6Core.dll" "$dist/"
cp "$root/bin/Qt6Gui.dll" "$dist/"
cp "$root/bin/Qt6Widgets.dll" "$dist/"
cp "$root/bin/libgcc_s_seh-1.dll" "$dist/"
cp "$root/bin/libstdc++-6.dll" "$dist/"
cp "$root/bin/libwinpthread-1.dll" "$dist/"
cp "$root/lib/qt6/plugins/platforms/qwindows.dll" "$dist/platforms/"
cp "$root/lib/qt6/plugins/imageformats/"*.dll "$dist/imageformats/"
find "$root/bin" -maxdepth 1 -name "*opencv*" -exec cp -t "$dist/" {} +
install -m 0644 readme.md "$dist/readme.md"
cat > "$dist/README.txt" <<'EOF'
chengnan Windows x64 package
Usage:
1. Extract the whole directory.
2. Double-click chengnan.exe to run.
Note:
- This package is cross-built on Linux with MinGW + Qt + OpenCV.
- Do not copy chengnan.exe alone; keep DLLs and Qt plugin directories together.
EOF
short_sha="${GITHUB_SHA::10}"
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
version="$GITHUB_REF_NAME"
else
version="build-$short_sha"
fi
package="$PACKAGE_BASENAME-$version.zip"
(cd dist-windows && zip -r "../artifacts/$package" chengnan)
sha256sum "artifacts/$package" > "artifacts/$package.sha256"
printf 'VERSION=%s\n' "$version" >> "$GITHUB_ENV"
printf 'PACKAGE=%s\n' "$package" >> "$GITHUB_ENV"
- name: Verify package
run: |
set -euo pipefail
test -s "artifacts/$PACKAGE"
test -s "artifacts/$PACKAGE.sha256"
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/chengnan.exe' > /dev/null
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/platforms/qwindows.dll' > /dev/null
unzip -l "artifacts/$PACKAGE" | grep -E 'chengnan/.*opencv.*\.dll' > /dev/null
sha256sum -c "artifacts/$PACKAGE.sha256"
- name: Upload package to repository release
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
set -euo pipefail
token="${RELEASE_TOKEN:-${GITHUB_TOKEN:-}}"
if [ -z "$token" ]; then
echo 'Missing release token. Configure RELEASE_TOKEN in repository secrets or ensure GITHUB_TOKEN is available.' >&2
exit 1
fi
server_url="${GITHUB_SERVER_URL%/}"
api_base="$server_url/api/v1/repos/$GITHUB_REPOSITORY"
tag_name="$VERSION"
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
prerelease=false
release_name="$GITHUB_REF_NAME"
else
prerelease=true
release_name="chengnan ${GITHUB_SHA::10}"
fi
release_payload=$(jq -n \
--arg tag_name "$tag_name" \
--arg target_commitish "$GITHUB_SHA" \
--arg name "$release_name" \
--arg body "Automated Windows x64 MinGW build from Linux Gitea Actions." \
--argjson prerelease "$prerelease" \
'{tag_name:$tag_name,target_commitish:$target_commitish,name:$name,body:$body,draft:false,prerelease:$prerelease}')
status=$(curl --silent --show-error --location \
--header "Authorization: token $token" \
--header 'Content-Type: application/json' \
--write-out '%{http_code}' \
--output release.json \
--data "$release_payload" \
"$api_base/releases")
if [ "$status" != "200" ] && [ "$status" != "201" ]; then
curl --silent --show-error --location \
--header "Authorization: token $token" \
--output release.json \
"$api_base/releases/tags/$tag_name"
fi
release_id=$(jq -r '.id' release.json)
if [ -z "$release_id" ] || [ "$release_id" = "null" ]; then
echo 'Failed to resolve release id.' >&2
cat release.json >&2
exit 1
fi
upload_asset() {
local path="$1"
local name
name=$(basename "$path")
curl --silent --show-error --location \
--header "Authorization: token $token" \
"$api_base/releases/$release_id/assets" > assets.json
jq -r --arg name "$name" '.[] | select(.name == $name) | .id' assets.json | while read -r asset_id; do
[ -n "$asset_id" ] && curl --silent --show-error --location \
--request DELETE \
--header "Authorization: token $token" \
"$api_base/releases/assets/$asset_id" >/dev/null
done
status=$(curl --silent --show-error --location \
--header "Authorization: token $token" \
--form "attachment=@$path;filename=$name" \
--write-out '%{http_code}' \
--output upload-response.json \
"$api_base/releases/$release_id/assets?name=$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))' "$name")")
if [ "$status" != "200" ] && [ "$status" != "201" ]; then
echo "Upload release asset failed, HTTP $status: $name" >&2
cat upload-response.json >&2
exit 1
fi
echo "Uploaded release asset: $name"
}
upload_asset "artifacts/$PACKAGE"
upload_asset "artifacts/$PACKAGE.sha256"
echo "Release assets uploaded to $server_url/$GITHUB_REPOSITORY/releases/tag/$tag_name"
+14
View File
@@ -0,0 +1,14 @@
build/
build-windows/
build-wsl-windows/
cmake-build-*/
.qt/
.qtc/
CMakeUserPresets.json
*.user
*.suo
*.vcxproj*
*.sln
*.exe
*.dll
*.pdb
+19 -32
View File
@@ -1,43 +1,30 @@
cmake_minimum_required(VERSION 3.16) cmake_minimum_required(VERSION 3.16)
project(chengnan VERSION 1.0.0 LANGUAGES CXX) project(QtOpenCVImageTool LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON) set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC OFF) set(CMAKE_AUTORCC ON)
set(CMAKE_AUTORCC OFF) set(CMAKE_AUTOUIC ON)
find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs) find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
find_package(OpenCV REQUIRED)
find_package(Qt6 QUIET COMPONENTS Widgets) add_executable(QtOpenCVImageTool WIN32
if (Qt6_FOUND) main.cpp
qt_add_executable(chengnan MainWindow.h
main.cpp MainWindow.cpp
MainWindow.h
MainWindow.cpp
)
target_link_libraries(chengnan PRIVATE Qt6::Widgets ${OpenCV_LIBS})
else()
find_package(Qt5 REQUIRED COMPONENTS Widgets)
add_executable(chengnan
main.cpp
MainWindow.h
MainWindow.cpp
)
target_link_libraries(chengnan PRIVATE Qt5::Widgets ${OpenCV_LIBS})
endif()
target_include_directories(chengnan PRIVATE ${OpenCV_INCLUDE_DIRS})
target_compile_definitions(chengnan PRIVATE
CHENGNAN_APP_VERSION="${PROJECT_VERSION}"
) )
if (MSVC) target_link_libraries(QtOpenCVImageTool PRIVATE
target_compile_options(chengnan PRIVATE /W4 /permissive-) Qt${QT_VERSION_MAJOR}::Widgets
else() ${OpenCV_LIBS}
target_compile_options(chengnan PRIVATE -Wall -Wextra -Wpedantic) )
endif()
install(TARGETS chengnan RUNTIME DESTINATION bin) target_include_directories(QtOpenCVImageTool PRIVATE ${OpenCV_INCLUDE_DIRS})
if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(QtOpenCVImageTool)
endif()
+301 -476
View File
@@ -1,608 +1,433 @@
#include "MainWindow.h" #include "MainWindow.h"
#include <QAction> #include <QCheckBox>
#include <QApplication>
#include <QFileDialog> #include <QFileDialog>
#include <QFileInfo> #include <QFileInfo>
#include <QImageReader> #include <QGroupBox>
#include <QImageWriter> #include <QHBoxLayout>
#include <QKeySequence> #include <QImage>
#include <QMenuBar> #include <QLabel>
#include <QMessageBox> #include <QMessageBox>
#include <QMouseEvent> #include <QPushButton>
#include <QScrollBar> #include <QPixmap>
#include <QScrollArea>
#include <QSlider> #include <QSlider>
#include <QSplitter>
#include <QStatusBar> #include <QStatusBar>
#include <QThread> #include <QThread>
#include <QToolBar> #include <QVBoxLayout>
#include <QTransform>
#include <opencv2/imgproc.hpp>
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <exception>
#include <memory>
namespace { namespace
cv::Mat qImageToMat(const QImage &image)
{ {
const QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
cv::Mat mat(rgba.height(), rgba.width(), CV_8UC4, const_cast<uchar *>(rgba.constBits()), rgba.bytesPerLine());
return mat.clone();
}
QImage matToQImage(const cv::Mat &mat) QImage matToQImage(const cv::Mat &mat)
{ {
if (mat.empty()) { if (mat.empty()) {
return {}; return {};
} }
cv::Mat rgba; cv::Mat rgb;
if (mat.channels() == 1) { if (mat.channels() == 1) {
cv::cvtColor(mat, rgba, cv::COLOR_GRAY2RGBA); cv::cvtColor(mat, rgb, cv::COLOR_GRAY2RGB);
} else if (mat.channels() == 3) { } else if (mat.channels() == 3) {
cv::cvtColor(mat, rgba, cv::COLOR_BGR2RGBA); cv::cvtColor(mat, rgb, cv::COLOR_BGR2RGB);
} else if (mat.channels() == 4) {
cv::cvtColor(mat, rgb, cv::COLOR_BGRA2RGBA);
} else { } else {
cv::cvtColor(mat, rgba, cv::COLOR_BGRA2RGBA); return {};
} }
return QImage(rgba.data, rgba.cols, rgba.rows, static_cast<int>(rgba.step), QImage::Format_RGBA8888).copy(); const QImage::Format format = rgb.channels() == 4 ? QImage::Format_RGBA8888 : QImage::Format_RGB888;
return QImage(rgb.data, rgb.cols, rgb.rows, static_cast<int>(rgb.step), format).copy();
} }
QImage extractObjectImage(const QImage &image) cv::Mat rotateWithBounds(const cv::Mat &image, double angle)
{ {
const cv::Mat rgba = qImageToMat(image); if (image.empty() || std::abs(angle) < 0.01) {
cv::Mat gray; return image.clone();
cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY); }
cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0.0);
cv::Mat edges; const cv::Point2f center(image.cols / 2.0F, image.rows / 2.0F);
cv::Canny(gray, edges, 60, 160); cv::Mat matrix = cv::getRotationMatrix2D(center, angle, 1.0);
const cv::Rect2f bounds = cv::RotatedRect(cv::Point2f(), image.size(), angle).boundingRect2f();
matrix.at<double>(0, 2) += bounds.width / 2.0 - image.cols / 2.0;
matrix.at<double>(1, 2) += bounds.height / 2.0 - image.rows / 2.0;
cv::Mat rotated;
const cv::Size outputSize(static_cast<int>(bounds.width), static_cast<int>(bounds.height));
cv::warpAffine(image, rotated, matrix, outputSize, cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(30, 30, 30));
return rotated;
}
cv::Mat translateImage(const cv::Mat &image, int dx, int dy)
{
if (image.empty() || (dx == 0 && dy == 0)) {
return image.clone();
}
cv::Mat translated;
cv::Mat matrix = (cv::Mat_<double>(2, 3) << 1, 0, dx, 0, 1, dy);
cv::warpAffine(image, translated, matrix, image.size(), cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(30, 30, 30));
return translated;
}
cv::Mat extractTargets(const cv::Mat &image, int &targetCount)
{
targetCount = 0;
if (image.empty()) {
return {};
}
cv::Mat gray;
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
cv::GaussianBlur(gray, gray, cv::Size(5, 5), 0);
cv::Mat binary;
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
if (cv::countNonZero(binary) > binary.rows * binary.cols / 2) {
cv::bitwise_not(binary, binary);
}
const cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5));
cv::morphologyEx(binary, binary, cv::MORPH_OPEN, kernel);
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, kernel);
std::vector<std::vector<cv::Point>> contours; std::vector<std::vector<cv::Point>> contours;
cv::findContours(edges, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
cv::Mat extracted = cv::Mat::zeros(image.size(), image.type());
image.copyTo(extracted, binary);
cv::Mat output = rgba.clone();
cv::cvtColor(output, output, cv::COLOR_RGBA2BGRA);
int count = 0;
for (const auto &contour : contours) { for (const auto &contour : contours) {
const double area = cv::contourArea(contour); const double area = cv::contourArea(contour);
if (area < 120.0) { if (area < 300.0) {
continue; continue;
} }
const cv::Rect rect = cv::boundingRect(contour);
cv::rectangle(output, rect, cv::Scalar(0, 0, 255, 255), 2); ++targetCount;
++count; cv::rectangle(extracted, cv::boundingRect(contour), cv::Scalar(0, 255, 0), 2);
} }
cv::putText(output, return extracted;
"objects: " + std::to_string(count),
cv::Point(16, 32),
cv::FONT_HERSHEY_SIMPLEX,
0.9,
cv::Scalar(0, 0, 255, 255),
2);
return matToQImage(output);
} }
QImage classifyImageByOpenCv(const QImage &image) QString classifyImage(const cv::Mat &image, int targetCount)
{ {
const cv::Mat rgba = qImageToMat(image); if (image.empty()) {
cv::Mat gray; return QStringLiteral("未载入图片");
cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY);
cv::Mat edges;
cv::Canny(gray, edges, 80, 180);
const double brightness = cv::mean(gray)[0];
const double edgeRatio = static_cast<double>(cv::countNonZero(edges)) / static_cast<double>(gray.total());
std::string label;
if (brightness < 80.0) {
label = "class: dark image";
} else if (edgeRatio > 0.12) {
label = "class: rich edges";
} else {
label = "class: bright smooth image";
} }
cv::Mat output = rgba.clone(); cv::Scalar mean = cv::mean(image);
cv::cvtColor(output, output, cv::COLOR_RGBA2BGRA); const double brightness = (mean[0] + mean[1] + mean[2]) / 3.0;
const int boxWidth = std::max(1, std::min(520, output.cols - 16)); const QString light = brightness >= 170.0 ? QStringLiteral("偏亮")
cv::rectangle(output, cv::Rect(8, 8, boxWidth, 52), cv::Scalar(0, 0, 0, 180), cv::FILLED); : brightness <= 85.0 ? QStringLiteral("偏暗")
cv::putText(output, : QStringLiteral("亮度适中");
label,
cv::Point(18, 42),
cv::FONT_HERSHEY_SIMPLEX,
0.8,
cv::Scalar(0, 255, 255, 255),
2);
return matToQImage(output);
}
} // namespace QString color = QStringLiteral("颜色均衡");
if (mean[2] > mean[1] + 18.0 && mean[2] > mean[0] + 18.0) {
ImageLabel::ImageLabel(QWidget *parent) color = QStringLiteral("红色占优");
: QLabel(parent) } else if (mean[1] > mean[2] + 18.0 && mean[1] > mean[0] + 18.0) {
{ color = QStringLiteral("绿色占优");
setAlignment(Qt::AlignCenter); } else if (mean[0] > mean[2] + 18.0 && mean[0] > mean[1] + 18.0) {
setBackgroundRole(QPalette::Base); color = QStringLiteral("蓝色占优");
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
setScaledContents(false);
setMinimumSize(320, 240);
setText(tr("打开一张图片开始查看"));
}
void ImageLabel::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
Q_EMIT doubleClicked();
} }
QLabel::mouseDoubleClickEvent(event);
return QStringLiteral("分类结果:%1,%2;目标数量:%3").arg(light, color).arg(targetCount);
}
class ImageProcessorWorker : public QObject
{
Q_OBJECT
public slots:
void process(const cv::Mat &source, const ProcessParams &params)
{
if (source.empty()) {
emit processed(cv::Mat(), QStringLiteral("未载入图片"));
return;
}
cv::Mat output = source.clone();
if (std::abs(params.scale - 1.0) > 0.001) {
cv::resize(output, output, cv::Size(), params.scale, params.scale, cv::INTER_LINEAR);
}
output = translateImage(output, params.translateX, params.translateY);
output = rotateWithBounds(output, params.angle);
int targetCount = 0;
if (params.extractTarget) {
output = extractTargets(output, targetCount);
} else {
cv::Mat gray;
cv::cvtColor(output, gray, cv::COLOR_BGR2GRAY);
cv::Mat binary;
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
targetCount = static_cast<int>(std::count_if(contours.begin(), contours.end(), [](const auto &contour) {
return cv::contourArea(contour) >= 300.0;
}));
}
const QString classText = params.classifyImage ? classifyImage(output, targetCount) : QStringLiteral("处理完成");
emit processed(output, classText);
}
signals:
void processed(const cv::Mat &image, const QString &classText);
};
} }
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) : QMainWindow(parent)
{ {
createActions(); qRegisterMetaType<cv::Mat>("cv::Mat");
createMenus(); qRegisterMetaType<ProcessParams>("ProcessParams");
createToolbar();
createCentralWidget();
updateActions();
setWindowTitle(tr("chengnan 图片处理工具")); buildUi();
resize(1200, 720);
statusBar()->showMessage(tr("就绪")); auto *worker = new ImageProcessorWorker;
workerThread = new QThread(this);
worker->moveToThread(workerThread);
connect(this, &MainWindow::processRequested, worker, &ImageProcessorWorker::process);
connect(worker, &ImageProcessorWorker::processed, this, &MainWindow::onProcessed);
connect(workerThread, &QThread::finished, worker, &QObject::deleteLater);
workerThread->start();
} }
void MainWindow::createActions() MainWindow::~MainWindow()
{ {
openAction_ = new QAction(tr("打开(&O)"), this); if (workerThread) {
openAction_->setShortcut(QKeySequence::Open); workerThread->quit();
connect(openAction_, &QAction::triggered, this, &MainWindow::openImage); workerThread->wait();
}
saveAction_ = new QAction(tr("保存(&S)"), this);
saveAction_->setShortcut(QKeySequence::Save);
connect(saveAction_, &QAction::triggered, this, &MainWindow::saveImage);
saveAsAction_ = new QAction(tr("另存为(&A)"), this);
saveAsAction_->setShortcut(QKeySequence::SaveAs);
connect(saveAsAction_, &QAction::triggered, this, &MainWindow::saveImageAs);
exitAction_ = new QAction(tr("退出(&X)"), this);
exitAction_->setShortcut(QKeySequence::Quit);
connect(exitAction_, &QAction::triggered, this, &QWidget::close);
zoomInAction_ = new QAction(tr("放大"), this);
zoomInAction_->setShortcut(QKeySequence::ZoomIn);
connect(zoomInAction_, &QAction::triggered, this, &MainWindow::zoomIn);
zoomOutAction_ = new QAction(tr("缩小"), this);
zoomOutAction_->setShortcut(QKeySequence::ZoomOut);
connect(zoomOutAction_, &QAction::triggered, this, &MainWindow::zoomOut);
fitAction_ = new QAction(tr("适配窗口"), this);
fitAction_->setShortcut(Qt::CTRL | Qt::Key_F);
connect(fitAction_, &QAction::triggered, this, &MainWindow::fitToWindow);
resetAction_ = new QAction(tr("原始大小"), this);
resetAction_->setShortcut(Qt::CTRL | Qt::Key_0);
connect(resetAction_, &QAction::triggered, this, &MainWindow::resetView);
rotateLeftAction_ = new QAction(tr("左旋 90°"), this);
connect(rotateLeftAction_, &QAction::triggered, this, &MainWindow::rotateLeft);
rotateRightAction_ = new QAction(tr("右旋 90°"), this);
connect(rotateRightAction_, &QAction::triggered, this, &MainWindow::rotateRight);
flipHorizontalAction_ = new QAction(tr("水平翻转"), this);
connect(flipHorizontalAction_, &QAction::triggered, this, &MainWindow::flipHorizontal);
flipVerticalAction_ = new QAction(tr("垂直翻转"), this);
connect(flipVerticalAction_, &QAction::triggered, this, &MainWindow::flipVertical);
grayscaleAction_ = new QAction(tr("灰度化"), this);
connect(grayscaleAction_, &QAction::triggered, this, &MainWindow::grayscale);
invertAction_ = new QAction(tr("反色"), this);
connect(invertAction_, &QAction::triggered, this, &MainWindow::invertColors);
extractAction_ = new QAction(tr("目标提取"), this);
connect(extractAction_, &QAction::triggered, this, &MainWindow::extractObjects);
classifyAction_ = new QAction(tr("简单分类"), this);
connect(classifyAction_, &QAction::triggered, this, &MainWindow::classifyImage);
} }
void MainWindow::createMenus() void MainWindow::buildUi()
{ {
QMenu *fileMenu = menuBar()->addMenu(tr("文件(&F)")); setWindowTitle(QStringLiteral("Qt + OpenCV 图像显示与处理"));
fileMenu->addAction(openAction_);
fileMenu->addAction(saveAction_);
fileMenu->addAction(saveAsAction_);
fileMenu->addSeparator();
fileMenu->addAction(exitAction_);
QMenu *viewMenu = menuBar()->addMenu(tr("查看(&V)")); auto *central = new QWidget(this);
viewMenu->addAction(zoomInAction_); auto *rootLayout = new QVBoxLayout(central);
viewMenu->addAction(zoomOutAction_);
viewMenu->addAction(fitAction_);
viewMenu->addAction(resetAction_);
QMenu *processMenu = menuBar()->addMenu(tr("处理(&P)")); auto *buttonLayout = new QHBoxLayout;
processMenu->addAction(rotateLeftAction_); openButton = new QPushButton(QStringLiteral("打开图片"));
processMenu->addAction(rotateRightAction_); saveButton = new QPushButton(QStringLiteral("保存图片"));
processMenu->addAction(flipHorizontalAction_); saveAsButton = new QPushButton(QStringLiteral("另存图片"));
processMenu->addAction(flipVerticalAction_); resetButton = new QPushButton(QStringLiteral("重置处理"));
processMenu->addSeparator(); buttonLayout->addWidget(openButton);
processMenu->addAction(grayscaleAction_); buttonLayout->addWidget(saveButton);
processMenu->addAction(invertAction_); buttonLayout->addWidget(saveAsButton);
processMenu->addSeparator(); buttonLayout->addStretch();
processMenu->addAction(extractAction_); buttonLayout->addWidget(resetButton);
processMenu->addAction(classifyAction_);
}
void MainWindow::createToolbar() auto *controlBox = new QGroupBox(QStringLiteral("图像处理"));
{ auto *controlLayout = new QHBoxLayout(controlBox);
QToolBar *toolbar = addToolBar(tr("主工具栏"));
toolbar->setMovable(false);
toolbar->addAction(openAction_);
toolbar->addAction(saveAction_);
toolbar->addSeparator();
toolbar->addAction(zoomOutAction_);
zoomSlider_ = new QSlider(Qt::Horizontal, this); scaleSlider = new QSlider(Qt::Horizontal);
zoomSlider_->setRange(10, 400); scaleSlider->setRange(25, 200);
zoomSlider_->setValue(100); scaleSlider->setValue(100);
zoomSlider_->setFixedWidth(180); rotateSlider = new QSlider(Qt::Horizontal);
zoomSlider_->setToolTip(tr("缩放比例")); rotateSlider->setRange(-180, 180);
connect(zoomSlider_, &QSlider::valueChanged, this, &MainWindow::updateZoomFromSlider); translateXSlider = new QSlider(Qt::Horizontal);
toolbar->addWidget(zoomSlider_); translateXSlider->setRange(-200, 200);
translateYSlider = new QSlider(Qt::Horizontal);
translateYSlider->setRange(-200, 200);
extractCheckBox = new QCheckBox(QStringLiteral("目标提取"));
classifyCheckBox = new QCheckBox(QStringLiteral("图像分类"));
toolbar->addAction(zoomInAction_); auto addSlider = [controlLayout](const QString &name, QSlider *slider) {
toolbar->addAction(fitAction_); auto *box = new QWidget;
toolbar->addSeparator(); auto *layout = new QVBoxLayout(box);
toolbar->addAction(rotateLeftAction_); layout->setContentsMargins(0, 0, 0, 0);
toolbar->addAction(rotateRightAction_); layout->addWidget(new QLabel(name));
toolbar->addAction(grayscaleAction_); layout->addWidget(slider);
toolbar->addAction(invertAction_); controlLayout->addWidget(box, 1);
toolbar->addAction(extractAction_); };
toolbar->addAction(classifyAction_);
}
void MainWindow::createCentralWidget() addSlider(QStringLiteral("缩放"), scaleSlider);
{ addSlider(QStringLiteral("旋转"), rotateSlider);
originalLabel_ = new ImageLabel(this); addSlider(QStringLiteral("水平平移"), translateXSlider);
processedLabel_ = new ImageLabel(this); addSlider(QStringLiteral("垂直平移"), translateYSlider);
originalLabel_->setText(tr("处理前图像")); controlLayout->addWidget(extractCheckBox);
processedLabel_->setText(tr("处理后图像")); controlLayout->addWidget(classifyCheckBox);
connect(originalLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
connect(processedLabel_, &ImageLabel::doubleClicked, this, &MainWindow::fitToWindow);
originalScrollArea_ = new QScrollArea(this); auto *imageLayout = new QHBoxLayout;
originalScrollArea_->setBackgroundRole(QPalette::Dark); originalLabel = new QLabel(QStringLiteral("原图"));
originalScrollArea_->setWidget(originalLabel_); resultLabel = new QLabel(QStringLiteral("处理后图像"));
originalScrollArea_->setWidgetResizable(true); originalLabel->setAlignment(Qt::AlignCenter);
resultLabel->setAlignment(Qt::AlignCenter);
originalLabel->setMinimumSize(480, 420);
resultLabel->setMinimumSize(480, 420);
originalLabel->setStyleSheet("QLabel { background:#202124; color:white; border:1px solid #555; }");
resultLabel->setStyleSheet("QLabel { background:#202124; color:white; border:1px solid #555; }");
processedScrollArea_ = new QScrollArea(this); auto *originalScroll = new QScrollArea;
processedScrollArea_->setBackgroundRole(QPalette::Dark); auto *resultScroll = new QScrollArea;
processedScrollArea_->setWidget(processedLabel_); originalScroll->setWidget(originalLabel);
processedScrollArea_->setWidgetResizable(true); resultScroll->setWidget(resultLabel);
originalScroll->setWidgetResizable(true);
resultScroll->setWidgetResizable(true);
auto *splitter = new QSplitter(Qt::Horizontal, this); imageLayout->addWidget(originalScroll, 1);
splitter->addWidget(originalScrollArea_); imageLayout->addWidget(resultScroll, 1);
splitter->addWidget(processedScrollArea_);
splitter->setStretchFactor(0, 1); rootLayout->addLayout(buttonLayout);
splitter->setStretchFactor(1, 1); rootLayout->addWidget(controlBox);
setCentralWidget(splitter); rootLayout->addLayout(imageLayout, 1);
setCentralWidget(central);
statusLabel = new QLabel(QStringLiteral("请打开一张图片"));
statusBar()->addWidget(statusLabel, 1);
connect(openButton, &QPushButton::clicked, this, &MainWindow::openImage);
connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveImage);
connect(saveAsButton, &QPushButton::clicked, this, &MainWindow::saveImageAs);
connect(resetButton, &QPushButton::clicked, this, &MainWindow::resetParams);
connect(scaleSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
connect(rotateSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
connect(translateXSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
connect(translateYSlider, &QSlider::valueChanged, this, &MainWindow::scheduleProcessing);
connect(extractCheckBox, &QCheckBox::toggled, this, &MainWindow::scheduleProcessing);
connect(classifyCheckBox, &QCheckBox::toggled, this, &MainWindow::scheduleProcessing);
} }
void MainWindow::openImage() void MainWindow::openImage()
{ {
const QString fileName = QFileDialog::getOpenFileName( const QString fileName = QFileDialog::getOpenFileName(
this, this,
tr("打开图片"), QStringLiteral("打开图片"),
QString(), QString(),
tr("图片文件 (*.png *.jpg *.jpeg *.bmp *.gif *.webp);;所有文件 (*.*)")); QStringLiteral("Images (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"));
if (fileName.isEmpty()) { if (fileName.isEmpty()) {
return; return;
} }
QImageReader reader(fileName); originalImage = cv::imread(fileName.toLocal8Bit().constData(), cv::IMREAD_COLOR);
reader.setAutoTransform(true); if (originalImage.empty()) {
const QImage image = reader.read(); QMessageBox::warning(this, QStringLiteral("打开失败"), QStringLiteral("无法读取该图片文件。"));
if (image.isNull()) {
QMessageBox::warning(this, tr("打开失败"), tr("无法读取图片:%1").arg(reader.errorString()));
return; return;
} }
setImage(image, fileName); savePath.clear();
updateOriginalView();
scheduleProcessing();
statusLabel->setText(QStringLiteral("已打开:%1").arg(QFileInfo(fileName).fileName()));
} }
void MainWindow::saveImage() void MainWindow::saveImage()
{ {
if (!ensureImageLoaded(tr("保存"))) { if (savePath.isEmpty()) {
return;
}
if (currentPath_.isEmpty()) {
saveImageAs(); saveImageAs();
return; return;
} }
writeImageToPath(currentPath_); if (writeResultToFile(savePath)) {
statusLabel->setText(QStringLiteral("已保存:%1").arg(QFileInfo(savePath).fileName()));
}
} }
void MainWindow::saveImageAs() void MainWindow::saveImageAs()
{ {
if (!ensureImageLoaded(tr("另存为"))) { if (resultImage.empty()) {
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("请先打开并处理图片。"));
return; return;
} }
const QString fileName = QFileDialog::getSaveFileName( const QString fileName = QFileDialog::getSaveFileName(
this, this,
tr("另存为"), QStringLiteral("另存图片"),
currentPath_.isEmpty() ? QStringLiteral("chengnan.png") : currentPath_, QStringLiteral("processed.png"),
tr("PNG 图片 (*.png);;JPEG 图片 (*.jpg *.jpeg);;BMP 图片 (*.bmp);;所有文件 (*.*)")); QStringLiteral("PNG (*.png);;JPEG (*.jpg *.jpeg);;BMP (*.bmp);;TIFF (*.tif *.tiff)"));
if (!fileName.isEmpty()) { if (fileName.isEmpty()) {
writeImageToPath(fileName);
}
}
void MainWindow::zoomIn()
{
setZoomFactor(zoomFactor_ * 1.25);
}
void MainWindow::zoomOut()
{
setZoomFactor(zoomFactor_ / 1.25);
}
void MainWindow::fitToWindow()
{
if (!ensureImageLoaded(tr("适配窗口"))) {
return; return;
} }
const QSize viewportSize = processedScrollArea_->viewport()->size(); if (writeResultToFile(fileName)) {
const QSize imageSize = currentImage_.size(); savePath = fileName;
if (imageSize.isEmpty()) { statusLabel->setText(QStringLiteral("已另存为:%1").arg(QFileInfo(fileName).fileName()));
}
}
void MainWindow::resetParams()
{
scaleSlider->setValue(100);
rotateSlider->setValue(0);
translateXSlider->setValue(0);
translateYSlider->setValue(0);
extractCheckBox->setChecked(false);
classifyCheckBox->setChecked(false);
scheduleProcessing();
}
void MainWindow::scheduleProcessing()
{
if (originalImage.empty()) {
return; return;
} }
const double xRatio = static_cast<double>(viewportSize.width()) / imageSize.width(); emit processRequested(originalImage.clone(), currentParams());
const double yRatio = static_cast<double>(viewportSize.height()) / imageSize.height();
setZoomFactor(std::min(xRatio, yRatio));
} }
void MainWindow::resetView() void MainWindow::onProcessed(const cv::Mat &image, const QString &classText)
{ {
setZoomFactor(1.0); resultImage = image.clone();
updateResultView();
statusLabel->setText(classText);
} }
void MainWindow::rotateLeft() void MainWindow::updateOriginalView()
{ {
if (!ensureImageLoaded(tr("旋转"))) { setImageOnLabel(originalLabel, originalImage);
return;
}
QTransform transform;
transform.rotate(-90);
applyTransformedImage(currentImage_.transformed(transform, Qt::SmoothTransformation));
} }
void MainWindow::rotateRight() void MainWindow::updateResultView()
{ {
if (!ensureImageLoaded(tr("旋转"))) { setImageOnLabel(resultLabel, resultImage);
return;
}
QTransform transform;
transform.rotate(90);
applyTransformedImage(currentImage_.transformed(transform, Qt::SmoothTransformation));
} }
void MainWindow::flipHorizontal() void MainWindow::setImageOnLabel(QLabel *label, const cv::Mat &mat)
{ {
if (!ensureImageLoaded(tr("翻转"))) { const QImage image = matToQImage(mat);
return; if (image.isNull()) {
} label->setText(QStringLiteral("无图像"));
applyTransformedImage(currentImage_.mirrored(true, false));
}
void MainWindow::flipVertical()
{
if (!ensureImageLoaded(tr("翻转"))) {
return;
}
applyTransformedImage(currentImage_.mirrored(false, true));
}
void MainWindow::grayscale()
{
processImageInThread(tr("灰度化"), tr("灰度化完成,可保存结果"), [](QImage image) {
cv::Mat rgba = qImageToMat(image);
cv::Mat gray;
cv::cvtColor(rgba, gray, cv::COLOR_RGBA2GRAY);
return matToQImage(gray);
});
}
void MainWindow::invertColors()
{
processImageInThread(tr("反色"), tr("反色完成,可保存结果"), [](QImage image) {
QImage result = image.convertToFormat(QImage::Format_ARGB32);
result.invertPixels(QImage::InvertRgb);
return result;
});
}
void MainWindow::extractObjects()
{
processImageInThread(tr("目标提取"), tr("目标提取完成,红框为提取到的目标"), [](QImage image) {
return extractObjectImage(image);
});
}
void MainWindow::classifyImage()
{
processImageInThread(tr("简单分类"), tr("简单分类完成,结果已标注在图像上"), [](QImage image) {
return classifyImageByOpenCv(image);
});
}
void MainWindow::updateZoomFromSlider(int value)
{
const double factor = static_cast<double>(value) / 100.0;
if (std::abs(factor - zoomFactor_) > 0.001) {
zoomFactor_ = factor;
updateImageView();
}
}
void MainWindow::setImage(const QImage &image, const QString &path)
{
originalImage_ = image.convertToFormat(QImage::Format_ARGB32);
currentImage_ = originalImage_;
currentPath_ = path;
setZoomFactor(1.0);
updateActions();
const QFileInfo info(path);
setWindowTitle(path.isEmpty()
? tr("chengnan 图片处理工具")
: tr("%1 - chengnan 图片处理工具").arg(info.fileName()));
statusBar()->showMessage(tr("已加载:%1 × %2").arg(currentImage_.width()).arg(currentImage_.height()), 5000);
}
void MainWindow::updateImageView()
{
if (currentImage_.isNull()) {
originalLabel_->setPixmap(QPixmap());
processedLabel_->setPixmap(QPixmap());
originalLabel_->setText(tr("处理前图像"));
processedLabel_->setText(tr("处理后图像"));
return; return;
} }
updateSingleView(originalLabel_, originalImage_); label->setPixmap(QPixmap::fromImage(image).scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
updateSingleView(processedLabel_, currentImage_);
const int sliderValue = static_cast<int>(zoomFactor_ * 100.0);
if (zoomSlider_->value() != sliderValue) {
zoomSlider_->blockSignals(true);
zoomSlider_->setValue(sliderValue);
zoomSlider_->blockSignals(false);
}
statusBar()->showMessage(tr("缩放:%1%").arg(sliderValue));
} }
void MainWindow::updateSingleView(ImageLabel *label, const QImage &image) ProcessParams MainWindow::currentParams() const
{ {
const QSize scaledSize( ProcessParams params;
std::max(1, static_cast<int>(std::round(image.width() * zoomFactor_))), params.scale = scaleSlider->value() / 100.0;
std::max(1, static_cast<int>(std::round(image.height() * zoomFactor_)))); params.angle = rotateSlider->value();
const QPixmap pixmap = QPixmap::fromImage(image).scaled( params.translateX = translateXSlider->value();
scaledSize, params.translateY = translateYSlider->value();
Qt::KeepAspectRatio, params.extractTarget = extractCheckBox->isChecked();
Qt::SmoothTransformation); params.classifyImage = classifyCheckBox->isChecked();
return params;
label->setText(QString());
label->setPixmap(pixmap);
label->resize(pixmap.size());
} }
void MainWindow::setZoomFactor(double factor) bool MainWindow::writeResultToFile(const QString &fileName)
{ {
zoomFactor_ = std::clamp(factor, 0.10, 4.00); if (resultImage.empty()) {
updateImageView(); QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("没有可保存的处理结果。"));
} return false;
void MainWindow::applyTransformedImage(const QImage &image, const QString &message)
{
currentImage_ = image.convertToFormat(QImage::Format_ARGB32);
updateImageView();
updateActions();
statusBar()->showMessage(message.isEmpty() ? tr("处理完成,可保存结果") : message, 3000);
}
void MainWindow::processImageInThread(const QString &actionName,
const QString &doneMessage,
const std::function<QImage(QImage)> &processor)
{
if (!ensureImageLoaded(actionName)) {
return;
}
const QImage input = currentImage_;
auto result = std::make_shared<QImage>();
auto error = std::make_shared<QString>();
QThread *thread = QThread::create([input, result, error, processor]() {
try {
*result = processor(input);
} catch (const cv::Exception &ex) {
*error = QString::fromLocal8Bit(ex.what());
} catch (const std::exception &ex) {
*error = QString::fromLocal8Bit(ex.what());
}
});
statusBar()->showMessage(tr("正在处理:%1 ...").arg(actionName));
connect(thread, &QThread::finished, this, [this, thread, result, error, doneMessage]() {
thread->deleteLater();
if (!error->isEmpty() || result->isNull()) {
QMessageBox::warning(this, tr("处理失败"), error->isEmpty() ? tr("处理结果为空。") : *error);
return;
}
applyTransformedImage(*result, doneMessage);
});
thread->start();
}
void MainWindow::updateActions()
{
const bool hasImage = !currentImage_.isNull();
saveAction_->setEnabled(hasImage);
saveAsAction_->setEnabled(hasImage);
zoomInAction_->setEnabled(hasImage);
zoomOutAction_->setEnabled(hasImage);
fitAction_->setEnabled(hasImage);
resetAction_->setEnabled(hasImage);
rotateLeftAction_->setEnabled(hasImage);
rotateRightAction_->setEnabled(hasImage);
flipHorizontalAction_->setEnabled(hasImage);
flipVerticalAction_->setEnabled(hasImage);
grayscaleAction_->setEnabled(hasImage);
invertAction_->setEnabled(hasImage);
extractAction_->setEnabled(hasImage);
classifyAction_->setEnabled(hasImage);
zoomSlider_->setEnabled(hasImage);
}
bool MainWindow::ensureImageLoaded(const QString &actionName) const
{
if (!currentImage_.isNull()) {
return true;
} }
QMessageBox::information(nullptr, actionName, tr("请先打开一张图片。"));
return false;
}
bool MainWindow::writeImageToPath(const QString &path) if (!cv::imwrite(fileName.toLocal8Bit().constData(), resultImage)) {
{ QMessageBox::warning(this, QStringLiteral("保存失败"), QStringLiteral("无法写入该图片文件。"));
QImageWriter writer(path);
if (!writer.write(currentImage_)) {
QMessageBox::warning(this, tr("保存失败"), tr("无法保存图片:%1").arg(writer.errorString()));
return false; return false;
} }
currentPath_ = path;
setWindowTitle(tr("%1 - chengnan 图片处理工具").arg(QFileInfo(path).fileName()));
statusBar()->showMessage(tr("已保存:%1").arg(path), 5000);
return true; return true;
} }
#include "MainWindow.moc"
+49 -73
View File
@@ -1,100 +1,76 @@
#ifndef MAINWINDOW_H #ifndef MAINWINDOW_H
#define MAINWINDOW_H #define MAINWINDOW_H
#include <QImage>
#include <QLabel>
#include <QMainWindow> #include <QMainWindow>
#include <QPixmap> #include <QMetaType>
#include <QScrollArea>
#include <QString>
#include <functional>
class QAction; #include <opencv2/opencv.hpp>
class QMenu;
class QLabel;
class QPushButton; class QPushButton;
class QSlider; class QSlider;
class QCheckBox;
class QThread;
class ImageLabel final : public QLabel struct ProcessParams
{ {
Q_OBJECT double scale = 1.0;
int translateX = 0;
public: int translateY = 0;
explicit ImageLabel(QWidget *parent = nullptr); double angle = 0.0;
bool extractTarget = false;
Q_SIGNALS: bool classifyImage = false;
void doubleClicked();
protected:
void mouseDoubleClickEvent(QMouseEvent *event) override;
}; };
class MainWindow final : public QMainWindow Q_DECLARE_METATYPE(cv::Mat)
Q_DECLARE_METATYPE(ProcessParams)
class MainWindow : public QMainWindow
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit MainWindow(QWidget *parent = nullptr); explicit MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
private Q_SLOTS: signals:
void processRequested(const cv::Mat &image, const ProcessParams &params);
private slots:
void openImage(); void openImage();
void saveImage(); void saveImage();
void saveImageAs(); void saveImageAs();
void zoomIn(); void resetParams();
void zoomOut(); void scheduleProcessing();
void fitToWindow(); void onProcessed(const cv::Mat &image, const QString &classText);
void resetView();
void rotateLeft();
void rotateRight();
void flipHorizontal();
void flipVertical();
void grayscale();
void invertColors();
void extractObjects();
void classifyImage();
void updateZoomFromSlider(int value);
private: private:
void createActions(); void buildUi();
void createMenus(); void updateOriginalView();
void createToolbar(); void updateResultView();
void createCentralWidget(); void setImageOnLabel(QLabel *label, const cv::Mat &mat);
void setImage(const QImage &image, const QString &path = QString()); ProcessParams currentParams() const;
void updateImageView(); bool writeResultToFile(const QString &fileName);
void updateSingleView(ImageLabel *label, const QImage &image);
void setZoomFactor(double factor);
void applyTransformedImage(const QImage &image, const QString &message = QString());
void processImageInThread(const QString &actionName, const QString &doneMessage, const std::function<QImage(QImage)> &processor);
void updateActions();
bool ensureImageLoaded(const QString &actionName) const;
bool writeImageToPath(const QString &path);
ImageLabel *originalLabel_ = nullptr; QLabel *originalLabel = nullptr;
ImageLabel *processedLabel_ = nullptr; QLabel *resultLabel = nullptr;
QScrollArea *originalScrollArea_ = nullptr; QLabel *statusLabel = nullptr;
QScrollArea *processedScrollArea_ = nullptr; QPushButton *openButton = nullptr;
QSlider *zoomSlider_ = nullptr; QPushButton *saveButton = nullptr;
QPushButton *saveAsButton = nullptr;
QPushButton *resetButton = nullptr;
QSlider *scaleSlider = nullptr;
QSlider *rotateSlider = nullptr;
QSlider *translateXSlider = nullptr;
QSlider *translateYSlider = nullptr;
QCheckBox *extractCheckBox = nullptr;
QCheckBox *classifyCheckBox = nullptr;
QImage originalImage_; cv::Mat originalImage;
QImage currentImage_; cv::Mat resultImage;
QString currentPath_; QString savePath;
double zoomFactor_ = 1.0;
QAction *openAction_ = nullptr; QThread *workerThread = nullptr;
QAction *saveAction_ = nullptr;
QAction *saveAsAction_ = nullptr;
QAction *exitAction_ = nullptr;
QAction *zoomInAction_ = nullptr;
QAction *zoomOutAction_ = nullptr;
QAction *fitAction_ = nullptr;
QAction *resetAction_ = nullptr;
QAction *rotateLeftAction_ = nullptr;
QAction *rotateRightAction_ = nullptr;
QAction *flipHorizontalAction_ = nullptr;
QAction *flipVerticalAction_ = nullptr;
QAction *grayscaleAction_ = nullptr;
QAction *invertAction_ = nullptr;
QAction *extractAction_ = nullptr;
QAction *classifyAction_ = nullptr;
}; };
#endif // MAINWINDOW_H #endif
Binary file not shown.
+46
View File
@@ -0,0 +1,46 @@
@echo off
setlocal
rem Usage:
rem build_windows.bat C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
rem build_windows.bat C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
if "%~1"=="" (
echo Usage: %~nx0 ^<QtDir^> ^<OpenCV_DIR^> [CMakeGenerator]
echo Example MSVC : %~nx0 C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
echo Example MinGW: %~nx0 C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
exit /b 1
)
if "%~2"=="" (
echo Missing OpenCV_DIR.
exit /b 1
)
set QT_DIR=%~1
set OPENCV_DIR=%~2
set GENERATOR=%~3
if "%GENERATOR%"=="" (
set GENERATOR=Visual Studio 17 2022
)
if not exist build-windows (
mkdir build-windows
)
if /I "%GENERATOR%"=="MinGW Makefiles" (
cmake -S . -B build-windows -G "%GENERATOR%" -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="%QT_DIR%" -DOpenCV_DIR="%OPENCV_DIR%"
) else (
cmake -S . -B build-windows -G "%GENERATOR%" -A x64 -DCMAKE_PREFIX_PATH="%QT_DIR%" -DOpenCV_DIR="%OPENCV_DIR%"
)
if errorlevel 1 exit /b %errorlevel%
cmake --build build-windows --config Release
if errorlevel 1 exit /b %errorlevel%
echo.
echo Build finished.
echo For MSVC, check: build-windows\Release\QtOpenCVImageTool.exe
echo For MinGW, check: build-windows\QtOpenCVImageTool.exe
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
set -euo pipefail
if ! command -v x86_64-w64-mingw32-g++ >/dev/null 2>&1; then
echo "Missing x86_64-w64-mingw32-g++."
echo "Install it in WSL with: sudo apt install mingw-w64"
exit 1
fi
if [[ "${QT_MINGW_PREFIX:-}" == "" ]]; then
echo "Missing QT_MINGW_PREFIX."
echo "Example: export QT_MINGW_PREFIX=/opt/mxe/usr/x86_64-w64-mingw32.shared/qt6"
exit 1
fi
if [[ "${OpenCV_DIR:-}" == "" ]]; then
echo "Missing OpenCV_DIR."
echo "Example: export OpenCV_DIR=/opt/mxe/usr/x86_64-w64-mingw32.shared/lib/cmake/opencv4"
exit 1
fi
cmake -S . -B build-wsl-windows \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw64.cmake \
-DCMAKE_PREFIX_PATH="${QT_MINGW_PREFIX}" \
-DOpenCV_DIR="${OpenCV_DIR}"
cmake --build build-wsl-windows --config Release
echo "Windows executable should be under build-wsl-windows/."
+11
View File
@@ -0,0 +1,11 @@
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)
set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
+2 -4
View File
@@ -5,12 +5,10 @@
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
QApplication app(argc, argv); QApplication app(argc, argv);
QApplication::setApplicationName(QStringLiteral("chengnan"));
QApplication::setApplicationVersion(QStringLiteral(CHENGNAN_APP_VERSION));
QApplication::setOrganizationName(QStringLiteral("luochen570"));
MainWindow window; MainWindow window;
window.resize(1180, 760);
window.show(); window.show();
return QApplication::exec(); return app.exec();
} }
+229 -124
View File
@@ -1,154 +1,259 @@
# chengnan # Qt + OpenCV 图像显示与处理
项目链接:<https://git.luochen570.cn/luochen570/chengnan> 本工程使用 Qt Widgets 设计界面,使用 OpenCV 完成图像处理。程序支持打开图片、保存图片、另存图片,支持缩放、平移、旋转,并提供目标提取和简单图像分类功能。图像显示使用 Qt 的 `QLabel`/`QWidget`,没有使用 `cv::imshow`。
`chengnan` 是一个 Windows 图像显示与处理课程项目,使用 **Qt Widgets + OpenCV + CMake + C++17** 开发。 ## 文件说明
## 作业要求对应情况 - `CMakeLists.txt`:CMake 工程配置。
- `main.cpp`:程序入口。
- 使用 Qt 设计界面:已使用 Qt Widgets 实现菜单栏、工具栏和双栏图像显示界面。 - `MainWindow.h`:主窗口类和处理参数声明。
- 打开图片、保存图片、另存图片:已实现。 - `MainWindow.cpp`:界面、图像读写、Qt 线程和 OpenCV 处理实现。
- 缩放、平移、旋转:
- 缩放:工具栏滑块、放大、缩小、原始大小、双击适配窗口。
- 平移:图片位于 `QScrollArea` 中,放大后可通过滚动条平移查看。
- 旋转:左旋 90°、右旋 90°。
- 图片处理:灰度化、反色、目标提取、简单分类。
- 处理前后对比:主界面左右两个 `QWidget` 区域分别显示处理前和处理后图像。
- 显示方式:使用 Qt Widgets 显示图片,未使用 `cv::imshow`。
- OpenCV 处理线程:灰度化、反色、目标提取、简单分类通过 Qt 线程执行,避免处理时阻塞界面。
- Windows 应用构建发布:`.gitea/workflows/build-windows-release.yml` 会在 Gitea Actions 的 Linux Runner 中交叉构建 Windows x64 程序并上传 Release 附件。
## 功能 ## 功能
当前实现: - 打开图片:读取 `png/jpg/bmp/tif` 等常见格式。
- 保存图片:保存当前处理结果。
- 另存图片:将处理结果保存为新文件。
- 显示对比:左侧显示处理前图像,右侧显示处理后图像。
- 基本处理:缩放、水平平移、垂直平移、旋转。
- 目标提取:使用灰度化、Otsu 阈值、形态学处理和轮廓检测提取前景目标,并用绿色矩形框标记目标。
- 图像分类:根据平均亮度和主色通道给出简单分类,同时显示目标数量。
- 线程处理:图像处理工作对象运行在 `QThread` 中,避免阻塞界面。
- 打开图片:PNG、JPG、JPEG、BMP、GIF、WebP 等 Qt 支持的格式 ## Windows 构建说明
- 保存当前处理后图片
- 另存为 PNG / JPG / BMP 等格式
- 处理前 / 处理后双栏对比显示
- 缩放:工具栏滑块、放大、缩小、原始大小
- 平移:放大后使用滚动条移动查看区域
- 双击图片适配窗口
- 旋转:左旋 90°、右旋 90°
- 翻转:水平翻转、垂直翻转
- OpenCV 图片处理:灰度化、目标提取、简单分类
- 其它处理:反色
## 文件结构 本工程使用 CMake 管理,目标是构建 Windows 桌面应用程序 `QtOpenCVImageTool.exe`。推荐使用 **MSVC 64 位**,因为 OpenCV 官方 Windows 预编译包通常就是 MSVC 版本,配置最省事。
构建时请保持三者一致:
- 编译器一致:MSVC 对 MSVC,MinGW 对 MinGW。
- 位数一致:建议全部使用 64 位。
- Qt、OpenCV、CMake 使用同一套构建环境。
如果使用 MSVC,则不要混用 MinGW 版 Qt;如果使用 MinGW,则不要直接使用 OpenCV 官方 MSVC 预编译包。
### 需要安装的软件
1. Visual Studio 2022 或 Visual Studio 2022 Build Tools
安装时勾选:
```text ```text
chengnan/ Desktop development with C++
├── .gitea/workflows/build-windows-release.yml MSVC v143 x64/x86 build tools
├── CMakeLists.txt Windows 10 SDK 或 Windows 11 SDK
├── MainWindow.cpp C++ CMake tools for Windows
├── MainWindow.h
├── main.cpp
└── readme.md
``` ```
除工作流和 `readme.md` 外,工程根目录只保留 `CMakeLists.txt`、`main.cpp`、`MainWindow.h`、`MainWindow.cpp` 四个文件。 安装完成后,系统中应能找到类似路径:
## Windows 编译需要的工具
推荐环境:Windows 10 / Windows 11 x64。
必须安装:
1. **Git for Windows**
- 下载:<https://git-scm.com/download/win>
- 用于克隆项目源码。
2. **CMake 3.16 或更高版本**
- 下载:<https://cmake.org/download/>
- 安装时建议勾选 `Add CMake to the system PATH`。
3. **Qt 6 或 Qt 5,包含 Widgets 模块**
- 下载:<https://www.qt.io/download-qt-installer-oss>
- 推荐安装 Qt 6.x 的 MSVC 64-bit 套件,例如 `msvc2019_64` 或 `msvc2022_64`。
4. **OpenCV 4.x Windows 预编译包**
- 下载:<https://opencv.org/releases/>
- 解压后 CMake 需要能找到 OpenCV 的 `build` 目录,例如 `C:\opencv\build`。
5. **Visual Studio 2022 Build Tools 或 Visual Studio 2022**
- 下载:<https://visualstudio.microsoft.com/zh-hans/downloads/>
- 需要安装组件:`使用 C++ 的桌面开发`。
- 提供 MSVC 编译器和 Windows SDK。
## 获取源码
```powershell
git clone https://git.luochen570.cn/luochen570/chengnan.git
cd chengnan
```
## 手动构建
在已配置 Visual Studio C++ 编译环境的 PowerShell 或 “x64 Native Tools Command Prompt for VS 2022” 中执行:
```powershell
cmake -S . -B build-windows -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH="C:\Qt\6.7.3\msvc2022_64;C:\opencv\build"
cmake --build build-windows --config Release
```
打包 Qt 运行库:
```powershell
C:\Qt\6.7.3\msvc2022_64\bin\windeployqt.exe --release --no-translations build-windows\Release\chengnan.exe
```
还需要把 OpenCV 的运行库 DLL(例如 `opencv_world4100.dll`)复制到 `chengnan.exe` 同目录。
## Gitea Actions / GitHub Actions 风格工作流
仓库中的 `.gitea/workflows/build-windows-release.yml` 使用 Linux Runner 的 Fedora 容器交叉构建 Windows x64 应用并发布 Release 附件:
- 安装 MinGW-w64、Qt MinGW、OpenCV MinGW 依赖
- 使用 `x86_64-w64-mingw32-cmake` 配置 Windows 目标程序
- 使用 Ninja 在 Linux 上交叉编译生成 `chengnan.exe`
- 打包 `chengnan.exe`、Qt DLL、OpenCV DLL、Qt 插件目录
- 上传 `.zip` 和 `.sha256` 到仓库 Release
发布上传使用仓库 Secret:`RELEASE_TOKEN`。如果没有配置该 Secret,工作流会尝试使用运行环境提供的 `GITHUB_TOKEN`。
## 常见问题
### 找不到 Qt
确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 Qt 套件目录,而不是 Qt 根目录。例如应使用:
```text ```text
C:\Qt\6.7.3\msvc2022_64 C:\Program Files\Microsoft Visual Studio\2022\Community
C:\Program Files\Microsoft Visual Studio\2022\BuildTools
``` ```
不要写成: 2. Qt for Windows
使用 Qt Online Installer 安装 Qt。推荐安装 Qt 6.x,并勾选 MSVC 64 位组件,例如:
```text ```text
C:\Qt Qt 6.6.x
MSVC 2019 64-bit 或 MSVC 2022 64-bit
Qt Creator
``` ```
### 找不到 OpenCV 安装完成后,Qt 路径通常类似:
确认 CMake 的 `CMAKE_PREFIX_PATH` 包含 OpenCV 的 `build` 目录。例如:
```text ```text
C:\opencv\build C:\Qt\6.6.0\msvc2019_64
C:\Qt\6.6.0\msvc2022_64
``` ```
该目录下通常能找到 `OpenCVConfig.cmake`。 该目录下应存在:
### 找不到 MSVC 编译器 ```text
C:\Qt\6.6.0\msvc2019_64\lib\cmake\Qt6\Qt6Config.cmake
```
请安装 Visual Studio 2022 的 `使用 C++ 的桌面开发`,然后在 “x64 Native Tools Command Prompt for VS 2022” 或已配置 VS 环境的 PowerShell 里运行构建命令。 3. OpenCV for Windows
### exe 复制到其它电脑无法运行 可以使用 OpenCV 官方 Windows 包。解压或安装到例如:
不要只复制单个 `chengnan.exe`。需要同时复制 Qt / OpenCV DLL 和 Qt 插件目录,或直接使用 Gitea Actions 发布的 zip 附件。 ```text
C:\opencv
```
## 开发说明 常见的 CMake 配置路径是:
- `main.cpp`:应用入口,创建并显示主窗口 ```text
- `MainWindow.h`:主窗口和图片标签类声明 C:\opencv\build\x64\vc16\lib
- `MainWindow.cpp`:菜单、工具栏、图片显示、OpenCV 图像处理和 Qt 线程逻辑 ```
- `CMakeLists.txt`:Qt Widgets + OpenCV CMake 构建配置
- `readme.md`:项目说明文档 该目录下应存在:
```text
C:\opencv\build\x64\vc16\lib\OpenCVConfig.cmake
```
4. CMake
如果安装 Visual Studio 时勾选了 CMake 工具,通常已经够用。也可以单独安装 CMake for Windows。命令行检查:
```bat
cmake --version
```
### 推荐方式:Qt Creator 构建
1. 打开 Qt Creator。
2. 选择“打开项目”,打开本目录的 `CMakeLists.txt`。
3. 选择 Windows Kit,例如:
```text
Desktop Qt 6.x.x MSVC 2019 64-bit
Desktop Qt 6.x.x MSVC 2022 64-bit
```
4. 如果 CMake 找不到 OpenCV,在 Qt Creator 的 CMake 配置项中添加:
```text
OpenCV_DIR=C:/opencv/build/x64/vc16/lib
```
5. 配置完成后点击“构建”。
6. 构建成功后会生成 `QtOpenCVImageTool.exe`。
7. 在 Qt Creator 中点击“运行”即可启动程序。
### 命令行构建:MSVC
打开开始菜单中的:
```text
x64 Native Tools Command Prompt for VS 2022
```
进入工程目录,例如:
```bat
cd /d D:\QtOpenCVImageTool
```
使用项目提供的脚本构建:
```bat
build_windows.bat C:\Qt\6.6.0\msvc2019_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
```
如果你的 Qt 是 MSVC 2022 版本,路径可改为:
```bat
build_windows.bat C:\Qt\6.6.0\msvc2022_64 C:\opencv\build\x64\vc16\lib "Visual Studio 17 2022"
```
也可以手动执行 CMake:
```bat
mkdir build-windows
cd build-windows
cmake .. -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH=C:\Qt\6.6.0\msvc2019_64 -DOpenCV_DIR=C:\opencv\build\x64\vc16\lib
cmake --build . --config Release
```
MSVC 生成的 exe 通常位于:
```text
build-windows\Release\QtOpenCVImageTool.exe
```
### 命令行构建:MinGW
如果使用 MinGW,需要安装 MinGW 版 Qt,并准备 MinGW 编译出来的 OpenCV。不要把 MSVC 版 OpenCV 直接给 MinGW 使用。
示例:
```bat
build_windows.bat C:\Qt\6.6.0\mingw_64 C:\opencv-mingw\install "MinGW Makefiles"
```
手动构建:
```bat
mkdir build-windows
cd build-windows
cmake .. -G "MinGW Makefiles" -DCMAKE_PREFIX_PATH=C:\Qt\6.6.0\mingw_64 -DOpenCV_DIR=C:\opencv-mingw\install
cmake --build . --config Release
```
MinGW 生成的 exe 通常位于:
```text
build-windows\QtOpenCVImageTool.exe
```
### 运行和发布
构建出来的 `QtOpenCVImageTool.exe` 运行时需要 Qt 和 OpenCV 的 DLL。开发阶段可以直接在 Qt Creator 中运行;如果要单独拷贝给别人运行,需要把依赖 DLL 一起放到 exe 目录。
MSVC Release 示例:
```bat
cd build-windows\Release
C:\Qt\6.6.0\msvc2019_64\bin\windeployqt.exe QtOpenCVImageTool.exe
copy C:\opencv\build\x64\vc16\bin\opencv_world*.dll .
```
如果 OpenCV 不是 `opencv_world*.dll`,则复制对应的 `opencv_*.dll` 到 exe 所在目录。
MinGW 示例:
```bat
cd build-windows
C:\Qt\6.6.0\mingw_64\bin\windeployqt.exe QtOpenCVImageTool.exe
copy C:\opencv-mingw\bin\opencv_*.dll .
```
### 常见问题
1. `Could not find Qt6`
说明 `CMAKE_PREFIX_PATH` 没有指向 Qt 安装目录。请确认路径类似:
```text
C:\Qt\6.6.0\msvc2019_64
```
2. `Could not find OpenCV`
说明 `OpenCV_DIR` 没有指向包含 `OpenCVConfig.cmake` 的目录。请搜索 `OpenCVConfig.cmake`,并把它所在目录传给 CMake。
3. 程序启动时报缺少 DLL
请运行 `windeployqt`,并把 OpenCV 的 DLL 复制到 exe 所在目录。
4. 链接时报 MSVC/MinGW 相关错误
通常是 Qt、OpenCV、编译器不匹配。MSVC 工程必须使用 MSVC 版 Qt 和 MSVC 版 OpenCV;MinGW 工程必须使用 MinGW 版 Qt 和 MinGW 版 OpenCV。
## WSL 中交叉编译 Windows 程序
WSL 里不能使用 Linux 版 Qt/OpenCV 直接生成 Windows exe,必须准备 Windows 目标库。推荐使用 MinGW-w64 作为交叉编译器,并准备同为 MinGW-w64 目标的 Qt 和 OpenCV。
需要的组件:
- `x86_64-w64-mingw32-g++`
- Windows/MinGW 目标 Qt,目录中应包含 `Qt6Config.cmake` 或 `Qt5Config.cmake`
- Windows/MinGW 目标 OpenCV,目录中应包含 `OpenCVConfig.cmake`
构建脚本:
```bash
export QT_MINGW_PREFIX=/opt/mxe/usr/x86_64-w64-mingw32.shared/qt6
export OpenCV_DIR=/opt/mxe/usr/x86_64-w64-mingw32.shared/lib/cmake/opencv4
./build_wsl_windows.sh
```
如果使用的是自己编译或复制来的 Windows 目标 Qt/OpenCV,把上面两个路径换成实际路径即可。
## 说明
本示例中的分类属于简单规则分类,适合作为课程作业演示:根据图像整体亮度判断“偏亮/偏暗/亮度适中”,根据 BGR 平均值判断主色。若需要更高精度分类,可替换为训练好的 OpenCV DNN 或传统机器学习模型。