sobel only allow 31 kernel size as a max i want more can reimplemet sobel function : #include <opencv2/opencv.hpp>
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include <condition_variable>
namespace fs = std::filesystem; // For filesystem operations
// Function to compute gradient in x-direction using larger Sobel kernel
cv::Mat gradientx(const cv::Mat &img)
{
cv::Mat grad_x;
cv::Sobel(img, grad_x, CV_32F, 1, 0, 31);
return grad_x;
}
// Function to compute gradient in y-direction using larger Sobel kernel
cv::Mat gradienty(const cv::Mat &img)
{
cv::Mat grad_y;
cv::Sobel(img, grad_y, CV_32F, 0, 1, 31);
return grad_y;
}
// Function to check if line differences match expected pattern
bool checkMatch(const std::vector &lineset)
{
std::vector linediff(lineset.size());
std::adjacent_difference(lineset.begin(), lineset.end(), linediff.begin());
linediff.erase(linediff.begin()); // Remove the first element which is not valid
code
int x = 0;
int cnt = 0;
for (const auto &line : linediff)
{
if (std::abs(line - x) < 5)
{
cnt++;
}
else
{
cnt = 0;
x = line;
}
}
return cnt >= 5;
}
// Function to prune lines near the margins and match expected patterns
std::vector pruneLines(std::vector lineset, int image_dim, int margin = 20)
{
// Remove lines near the margins
lineset.erase(
std::remove_if(lineset.begin(), lineset.end(), [margin, image_dim](int x)
{ return x <= margin || x >= image_dim - margin; }),
lineset.end());
code
if (lineset.empty())
{
return lineset;
}
std::vector<int> linediff(lineset.size());
std::adjacent_difference(lineset.begin(), lineset.end(), linediff.begin());
linediff.erase(linediff.begin()); // Remove the first element which is not valid
int x = 0;
int cnt = 0;
int start_pos = 0;
for (size_t i = 0; i < linediff.size(); ++i)
{
int line = linediff[i];
if (std::abs(line - x) < 5)
{
cnt++;
if (cnt >= 5)
{
size_t end_pos = i + 2;
return std::vector<int>(lineset.begin() + start_pos, lineset.begin() + end_pos);
}
}
else
{
cnt = 0;
x = line;
start_pos = i;
}
}
return lineset;
Assistant
}
// Function to skeletonize a 1D signal
std::vector skeletonize_1d(const std::vector &arr)
{
std::vector _arr = arr;
code
for (size_t i = 0; i < _arr.size() - 1; ++i)
{
if (_arr[i] <= _arr[i + 1])
{
_arr[i] = 0;
}
}
for (size_t i = _arr.size() - 1; i > 0; --i)
{
if (_arr[i - 1] > _arr[i])
{
_arr[i] = 0;
}
}
return _arr;
}
// Function to perform 1D convolution
std::vector convolve1D(const std::vector &signal, const std::vector &kernel)
{
int signal_size = signal.size();
int kernel_size = kernel.size();
int conv_size = signal_size + kernel_size - 1;
std::vector conv(conv_size, 0.0);
code
for (int i = 0; i < conv_size; ++i)
{
int kmin = (i >= kernel_size - 1) ? i - (kernel_size - 1) : 0;
int kmax = (i < signal_size - 1) ? i : signal_size - 1;
for (int j = kmin; j <= kmax; ++j)
{
conv[i] += signal[j] * kernel[i - j];
}
}
// Trim to original signal size
int trim = (kernel_size - 1) / 2;
std::vector<double> result(signal_size);
for (int i = 0; i < signal_size; ++i)
{
result[i] = conv[i + trim];
}
return result;
}
// Function to get chessboard lines from Hough transform signals
std::tuple<std::vector, std::vector, bool> getChessLines(const std::vector &hdx, const std::vector &hdy,
double hdx_thresh, double hdy_thresh, const cv::Size &image_shape)
{
// Generate Gaussian window
int window_size = 21;
double sigma = 8.0;
cv::Mat gaussMat = cv::getGaussianKernel(window_size, sigma, CV_64F);
std::vector gausswin(gaussMat.rows);
for (int i = 0; i < gaussMat.rows; ++i)
{
gausswin[i] = gaussMat.at(i, 0);
}
code
// Threshold signals
std::vector<double> hdx_thresh_binary(hdx.size());
std::vector<double> hdy_thresh_binary(hdy.size());
std::transform(hdx.begin(), hdx.end(), hdx_thresh_binary.begin(),
[hdx_thresh](double val)
{ return val > hdx_thresh ? 1.0 : 0.0; });
std::transform(hdy.begin(), hdy.end(), hdy_thresh_binary.begin(),
[hdy_thresh](double val)
{ return val > hdy_thresh ? 1.0 : 0.0; });
// Blur signals using convolution with Gaussian window
std::vector<double> blur_x = convolve1D(hdx_thresh_binary, gausswin);
std::vector<double> blur_y = convolve1D(hdy_thresh_binary, gausswin);
// Skeletonize signals
std::vector<double> skel_x = skeletonize_1d(blur_x);
std::vector<double> skel_y = skeletonize_1d(blur_y);
// Find line positions
std::vector<int> lines_x;
std::vector<int> lines_y;
for (size_t i = 0; i < skel_x.size(); ++i)
{
if (skel_x[i] > 0)
lines_x.push_back(static_cast<int>(i));
}
for (size_t i = 0; i < skel_y.size(); ++i)
{
if (skel_y[i] > 0)
lines_y.push_back(static_cast<int>(i));
}
// Prune lines
lines_x = pruneLines(lines_x, image_shape.width);
lines_y = pruneLines(lines_y, image_shape.height);
// Check if lines match expected pattern
bool is_match = (lines_x.size() == 7) && (lines_y.size() == 7) &&
checkMatch(lines_x) && checkMatch(lines_y);
return {lines_x, lines_y, is_match};
}
// Function to extract chessboard tiles from the image
std::vectorcv::Mat getChessTiles(const cv::Mat &img, const std::vector &lines_x, const std::vector &lines_y)
{
int stepx = static_cast(std::round(static_cast(lines_x[1] - lines_x[0])));
int stepy = static_cast(std::round(static_cast(lines_y[1] - lines_y[0])));
code
// Pad the image if necessary
int padl_x = 0, padr_x = 0, padl_y = 0, padr_y = 0;
if (lines_x.front() - stepx < 0)
{
padl_x = std::abs(lines_x.front() - stepx);
}
if (lines_x.back() + stepx > img.cols - 1)
{
padr_x = lines_x.back() + stepx - img.cols + 1;
}
if (lines_y.front() - stepy < 0)
{
padl_y = std::abs(lines_y.front() - stepy);
}
if (lines_y.back() + stepy > img.rows - 1)
{
padr_y = lines_y.back() + stepy - img.rows + 1;
}
cv::Mat img_padded;
cv::copyMakeBorder(img, img_padded, padl_y, padr_y, padl_x, padr_x, cv::BORDER_REPLICATE);
std::vector<int> setsx{lines_x.front() - stepx + padl_x};
std::vector<int> setsy{lines_y.front() - stepy + padl_y};
for (const auto &x : lines_x)
setsx.push_back(x + padl_x);
setsx.push_back(lines_x.back() + stepx + padl_x);
for (const auto &y : lines_y)
setsy.push_back(y + padl_y);
setsy.push_back(lines_y.back() + stepy + padl_y);
std::vector<cv::Mat> squares;
for (int j = 0; j < 8; ++j)
{
for (int i = 0; i < 8; ++i)
{
int x1 = setsx[i];
int x2 = setsx[i + 1];
int y1 = setsy[j];
int y2 = setsy[j + 1];
// Adjust sizes to ensure squares are of equal size
if ((x2 - x1) != stepx)
{
x2 = x1 + stepx;
}
if ((y2 - y1) != stepy)
{
y2 = y1 + stepy;
}
cv::Mat square = img_padded(cv::Range(y1, y2), cv::Range(x1, x2));
squares.push_back(square);
}
}
return squares;
}
// Function to process an individual image
void process_image(const std::string &image_path, const std::string &output_dir)
{
// Load the image
cv::Mat image = cv::imread(image_path);
if (image.empty())
{
std::cout << "Failed to load image: " << image_path << std::endl;
return;
}
// Main code
// Thread-safe queue for task distribution
template
class SafeQueue
{
private:
std::queue queue;
std::mutex mutex;
std::condition_variable cond;
// Worker function for thread pool
void worker(SafeQueue<std::pair<std::string, std::string>> &task_queue, std::mutex &cout_mutex)
{
std::pair<std::string, std::string> task;
while (task_queue.pop(task))
{
process_image(task.first, task.second);
{
std::lock_guardstd::mutex lock(cout_mutex);
std::cout << "Processed: " << task.first << std::endl;
}
}
}
// Main function with threading
int main()
{
try
{
std::string input_folder = "train_images";
std::string output_folder = "tiles";
code
fs::create_directories(output_folder);
SafeQueue<std::pair<std::string, std::string>> task_queue;
std::mutex cout_mutex;
// Populate the task queue
for (const auto &entry : fs::directory_iterator(input_folder))
{
if (entry.is_regular_file())
{
std::string filename = entry.path().filename().string();
std::string extension = entry.path().extension().string();
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
if (extension == ".png" || extension == ".jpg" || extension == ".jpeg")
{
std::string image_path = entry.path().string();
task_queue.push({image_path, output_folder});
}
}
}
// Create thread pool
unsigned int num_threads = std::thread::hardware_concurrency();
std::vector<std::thread> threads;
for (unsigned int i = 0; i < num_threads; ++i)
{
threads.emplace_back(worker, std::ref(task_queue), std::ref(cout_mutex));
}
// Wait for all threads to complete
for (auto &thread : threads)
{
thread.join();
}
std::cout << "All images processed." << std::endl;
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
OpenCV's built-in cv::Sobel function restricts the maximum kernel size to 31. If you require larger kernel sizes for gradient computation, you can implement custom Sobel-like operators. One effective approach is to use the Derivative of Gaussian (DoG) method, which allows you to compute image gradients with arbitrary kernel sizes by separating the smoothing and differentiation steps.
Below, I'll guide you through reimplementing the gradientx and gradienty functions to support larger kernel sizes. This involves creating custom derivative Gaussian kernels and applying them using separable filtering for efficiency.
Overview of the Approach
Generate Derivative Gaussian Kernels: Create 1D Gaussian and its derivative kernels based on the desired kernel size and standard deviation (sigma).
Apply Separable Filtering: Use OpenCV's cv::sepFilter2D to apply the Gaussian smoothing and derivative operations separately, which is computationally efficient.
Replace Existing Gradient Functions: Utilize these custom functions in your existing image processing pipeline.
Step-by-Step Implementation
1. Helper Function to Generate Derivative of Gaussian Kernels
First, define a helper function to create a 1D derivative of Gaussian kernel. This function generates both the Gaussian and its derivative based on the specified kernel size and sigma.
cpp
#include <opencv2/opencv.hpp>
#include <vector>
#include <cmath>
// Function to create 1D Gaussian and its derivative kernels
std::pair<std::vector<double>, std::vector<double>> createGaussianAndDerivative(int ksize, double sigma) {
std::vector<double> gaussian(ksize);
std::vector<double> derivative(ksize);
int half_size = ksize / 2;
double sum = 0.0;
double deriv_sum = 0.0;
for (int i = 0; i < ksize; ++i) {
int x = i - half_size;
double g = std::exp(-(x * x) / (2 * sigma * sigma));
gaussian[i] = g;
derivative[i] = -x * g / (sigma * sigma); // dG/dx
sum += g;
// For symmetry, derivative sums to zero, but include if needed
deriv_sum += derivative[i];
}
// Normalize the Gaussian kernel
for (auto &val : gaussian) {
val /= sum;
}
// Normalize the derivative kernel to have zero mean (optional)
// Already zero mean due to symmetry
return {gaussian, derivative};
}
2. Custom Gradient Functions
Next, implement the gradientx and gradienty functions using the derivative of Gaussian kernels. These functions allow for arbitrary kernel sizes beyond the OpenCV limit.
cpp
// Function to compute gradient in x-direction using larger Sobel-like kernel
cv::Mat gradientx_custom(const cv::Mat &img, int ksize, double sigma) {
// Create Gaussian and derivative kernels
auto [gaussian, derivative] = createGaussianAndDerivative(ksize, sigma);
// Convert kernels to cv::Mat
cv::Mat gauss_kernel(1, ksize, CV_64F, gaussian.data());
cv::Mat deriv_kernel(1, ksize, CV_64F, derivative.data());
cv::Mat grad_x;
// Apply separable filter: first derivative in x, Gaussian in y
cv::sepFilter2D(img, grad_x, CV_32F, deriv_kernel, gauss_kernel, cv::Point(-1, -1), 0, cv::BORDER_REPLICATE);
return grad_x;
}
// Function to compute gradient in y-direction using larger Sobel-like kernel
cv::Mat gradienty_custom(const cv::Mat &img, int ksize, double sigma) {
// Create Gaussian and derivative kernels
auto [gaussian, derivative] = createGaussianAndDerivative(ksize, sigma);
// Convert kernels to cv::Mat
cv::Mat gauss_kernel(1, ksize, CV_64F, gaussian.data());
cv::Mat deriv_kernel(1, ksize, CV_64F, derivative.data());
cv::Mat grad_y;
// Apply separable filter: Gaussian in x, derivative in y
cv::sepFilter2D(img, grad_y, CV_32F, gauss_kernel, deriv_kernel, cv::Point(-1, -1), 0, cv::BORDER_REPLICATE);
return grad_y;
}
Parameters Explained:
ksize: Size of the kernel (must be odd).
sigma: Standard deviation for the Gaussian.
3. Integrate Custom Gradient Functions into Your Pipeline
Replace the existing gradientx and gradienty functions in your code with gradientx_custom and gradienty_custom. You can specify the desired kernel size and sigma based on your requirements.
cpp
// Replace existing gradientx and gradienty functions with custom implementations
cv::Mat gradientx(const cv::Mat &img)
{
int kernel_size = 51; // Example: larger than 31
double sigma = 10.0; // Adjust sigma as needed
return gradientx_custom(img, kernel_size, sigma);
}
cv::Mat gradienty(const cv::Mat &img)
{
int kernel_size = 51; // Example: larger than 31
double sigma = 10.0; // Adjust sigma as needed
return gradienty_custom(img, kernel_size, sigma);
}
Note: Choose ksize and sigma appropriately. A larger ksize typically requires a larger sigma to maintain the Gaussian's properties.
4. [Optional] Optimize for Performance
Using very large kernels can be computationally intensive. To optimize:
Ensure Kernel Size is Odd: Most convolution operations require odd-sized kernels to have a central pixel.
Use Separable Filters: The cv::sepFilter2D function efficiently applies the Gaussian and derivative operations in separate passes.
Adjust Sigma Appropriately: Avoid excessively large sigma values, which can lead to over-smoothing.
5. Full Integration Example
Here's how the modified sections of your code would look with the custom gradient functions:
cpp
// ... [Other includes and code above remain unchanged]
// Custom Gradient Functions (as defined above)
cv::Mat gradientx_custom(const cv::Mat &img, int ksize, double sigma) { /* ... */ }
cv::Mat gradienty_custom(const cv::Mat &img, int ksize, double sigma) { /* ... */ }
// Updated gradientx and gradienty functions
cv::Mat gradientx(const cv::Mat &img)
{
int kernel_size = 51; // Customize as needed
double sigma = 10.0; // Customize as needed
return gradientx_custom(img, kernel_size, sigma);
}
cv::Mat gradienty(const cv::Mat &img)
{
int kernel_size = 51; // Customize as needed
double sigma = 10.0; // Customize as needed
return gradienty_custom(img, kernel_size, sigma);
}
// ... [Rest of your code remains unchanged]
6. Complete Code Integration
For clarity, here's how the relevant parts of your original code would integrate with the custom gradient functions:
cpp
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <filesystem>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
namespace fs = std::filesystem;
// [Include the helper functions and custom gradient functions]
// ... [Rest of your existing code]
// Updated gradientx and gradienty functions using custom implementations
cv::Mat gradientx(const cv::Mat &img)
{
int kernel_size = 51; // Example kernel size
double sigma = 10.0; // Example sigma
return gradientx_custom(img, kernel_size, sigma);
}
cv::Mat gradienty(const cv::Mat &img)
{
int kernel_size = 51; // Example kernel size
double sigma = 10.0; // Example sigma
return gradienty_custom(img, kernel_size, sigma);
}
// ... [Continue with the rest of your image processing pipeline]
int main()
{
try
{
// [Your existing main function code]
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
Additional Considerations
Kernel Size vs. Sigma: Ensure that the sigma value is proportional to the ksize. A general rule of thumb is sigma ≈ ksize / 6. Adjust both based on the specific characteristics of your images.
Edge Handling: The cv::BORDER_REPLICATE border type is used to handle image borders. Depending on your application, other border types might be more suitable.
Performance: Larger kernels increase computational load. If real-time performance is needed, consider optimizing the kernel generation or leveraging hardware acceleration.
Validation: After implementing, validate the gradient outputs visually or by checking against smaller kernel sizes with known outputs to ensure correctness.
Conclusion
By implementing custom derivative of Gaussian filters, you can compute image gradients with arbitrary kernel sizes beyond OpenCV's built-in cv::Sobel limitations. This approach provides flexibility in gradient computation, allowing for more extensive smoothing and differentiation tailored to your specific image processing needs.
Feel free to adjust the ksize and sigma parameters to best suit your application. If you encounter performance issues with very large kernels, consider exploring further optimizations or leveraging hardware acceleration techniques.