Created
January 22, 2025 15:58
-
-
Save 27Cobalter/96c3eaa7a7addda43091fa1dcf6bd3a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cassert> | |
#include <numeric> | |
#include <print> | |
#include <cmath> | |
#include <filesystem> | |
#include <ranges> | |
#include <vector> | |
#include <opencv2/opencv.hpp> | |
auto main() -> int { | |
const std::filesystem::path rot_path("../../rect_rot.png"); | |
assert(std::filesystem::exists(rot_path)); | |
auto raw = cv::imread(rot_path.string(), cv::IMREAD_GRAYSCALE); | |
auto rows = cv::getOptimalDFTSize(raw.rows); | |
auto cols = cv::getOptimalDFTSize(raw.cols); | |
cv::Mat src; | |
cv::copyMakeBorder(raw, src, 0, 0, 0, rows - raw.rows, cols - raw.cols); | |
src.convertTo(src, CV_32FC1); | |
assert(src.type() == CV_32FC1); | |
cv::Mat rImg[] = {src, cv::Mat::zeros(src.size(), CV_32FC1)}; | |
cv::Mat fur; | |
cv::merge(rImg, 2, fur); | |
cv::dft(fur, fur); | |
cv::Mat dstdiv[2]; | |
cv::Mat dst; | |
cv::split(fur, dstdiv); | |
cv::magnitude(dstdiv[0], dstdiv[1], dst); | |
dst += cv::Scalar::all(1); | |
cv::log(dst, dst); | |
cv::normalize(dst, dst, 0, 255, cv::NORM_MINMAX); | |
dst.convertTo(dst, CV_8UC1); | |
cv::resize(dst, dst, cv::Size(1024, 1024)); | |
cv::Mat bin = dst.clone(); | |
cv::threshold(dst, bin, 127, 255, cv::THRESH_BINARY); | |
std::vector<cv::Vec4i> lines; | |
cv::HoughLinesP(bin, lines, 1, CV_PI / 180, 512, 512, 100); | |
cv::Mat paint = bin.clone(); | |
double rad; | |
for (auto& line : lines | std::views::take(32)) { | |
cv::line(paint, cv::Point(line[0], line[1]), cv::Point(line[2], line[3]), 255, 3, 8); | |
double tmp_rad = std::atan2(line[3] - line[1], line[2] - line[0]) / CV_PI * 180; | |
std::println("rad = {}", tmp_rad); | |
if (tmp_rad > std::numeric_limits<double>::epsilon() || | |
std::abs((std::abs(tmp_rad) - 90)) > std::numeric_limits<double>::epsilon()) { | |
rad = tmp_rad; | |
} | |
} | |
cv::Mat rot; | |
auto rotMat = cv::getRotationMatrix2D(cv::Point(src.cols >> 1, src.rows >> 1), rad, 1.0); | |
cv::warpAffine(src, rot, rotMat, src.size()); | |
cv::imshow("src", src); | |
cv::imshow("dst", dst); | |
cv::imshow("bin", bin); | |
cv::imshow("paint", paint); | |
cv::imshow("rot", rot); | |
cv::waitKey(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment