|
发表于 2024-12-7 11:27:27
|
显示全部楼层
在使用`bitwise_and`函数时,确保`pattern`和`mask`有相同的尺寸和相同的类型(数据类型)。如果其中一个是一个小图案,需要在应用前调整为与目标区域大小(`dstRoi`)相同。
以下是确保`pattern`和`mask`具有相同尺寸和类型的方法,只需要在代码中做一些调整:
1. **创建标准化区域的掩码**:确保你的掩码每次应用时与`pattern`大小和位置对准。
2. **调整模式尺寸**:如果`pattern`尺寸与处理区域不同,考虑使用`resize`或者复制多个模式单位以覆盖整个区域。
以下是如何修复错误的一种方法:
- #include <opencv2/opencv.hpp>
- using namespace cv;
- // Function to create a halftone pattern
- void createHalftonePattern(Mat &pattern, int dotSpacing, double angle) {
- int size = dotSpacing * 2; // Ensure pattern can rotate
- pattern = Mat(size, size, CV_8UC1, Scalar(0));
- Point center(size / 2, size / 2);
- Mat rotationMatrix = getRotationMatrix2D(center, angle, 1);
- // Create initial pattern with a circle
- Mat tempPattern = Mat::zeros(size, size, CV_8UC1);
- circle(tempPattern, center, dotSpacing / 2, Scalar(255), FILLED);
- // Apply rotation to the pattern
- warpAffine(tempPattern, pattern, rotationMatrix, pattern.size());
- }
- // Function to apply the halftone effect
- void applyHalftonePattern(const Mat &src, Mat &dst, int dotSpacing, double angle) {
- Mat pattern;
- createHalftonePattern(pattern, dotSpacing, angle);
- dst = src.clone();
- for (int y = 0; y < src.rows; y += dotSpacing) {
- for (int x = 0; x < src.cols; x += dotSpacing) {
- Rect roi(x, y, dotSpacing, dotSpacing);
- if (x + dotSpacing > src.cols || y + dotSpacing > src.rows)
- continue;
- // Extract the ROI from the source
- Mat srcRoi = src(roi);
- // Create a mask from the ROI
- Mat mask;
- threshold(srcRoi, mask, 128, 255, THRESH_BINARY);
- // Copy the pattern to the same size as the ROI
- Mat fullPattern;
- pattern(Rect(0, 0, mask.cols, mask.rows)).copyTo(fullPattern);
- // Use bitwise_and to extract the components
- Mat dstRoi = dst(roi);
- bitwise_and(fullPattern, mask, dstRoi);
- }
- }
- }
- int main() {
- Mat img = imread("your_image_path.jpg", IMREAD_GRAYSCALE);
- if (img.empty()) {
- std::cerr << "Error: Cannot load image\n";
- return -1;
- }
- Mat halftoneImg;
- applyHalftonePattern(img, halftoneImg, 10, 45); // Example with dot size 10 and angle 45
- imshow("Halftone Image", halftoneImg);
- waitKey(0);
- return 0;
- }
复制代码
**关键点:**
- **ROI和模式对齐**:确保模式(`pattern`)在每个处理区域(`roi`)都是相同的大小。
- **分区和填充**:通过复制并使用正确的索引调整单个图案。
- **适配边界**:如果需要,确保你处理的区域不会超出图像边界。
使用以上修正确保模式在整个应用过程中对齐和适配目标区域的大小。调试过程中可以检查每次处理中的矩阵类型和大小确保兼容。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|