一道题---------- 学的不扎实 +一点啰嗦话

这篇文章展示了如何使用OpenCV库在C++中进行图像处理,包括读取图片、裁剪、边缘增强、霍夫圆检测以及轮廓检测。作者通过实例展示了如何找到并提取图像中的最大圆并裁剪出其周围的区域。
摘要由CSDN通过智能技术生成
#include <opencv2/opencv.hpp>  
#include<opencv2/xfeatures2d.hpp>
#include<opencv2/features2d.hpp>
#include <iostream>  
#include <utility> 
#include <vector> 


using namespace cv;
using namespace std;

bool compareCircles(const Vec3f& a, const Vec3f& b) {
    return a[2] < b[2]; // 按半径升序排列  
}

bool isCircleInsideImage(const Point& center, int radius, const Mat& image) {
    // 检查圆心是否在图像内  
    if (center.x - radius < 0 || center.x + radius >= image.cols ||
        center.y - radius < 0 || center.y + radius >= image.rows) {
        return false;
    }
    return true;
}
std::pair<cv::Mat, cv::Mat> cropImage()
{
    cv::Mat src = cv::imread("C:/Users/yzy/Desktop/img/2.bmp");
    if (src.empty())
    {
        std::cerr << "Could not open or find the image!" << std::endl;
        return std::make_pair(cv::Mat(), cv::Mat());;
    }
    // 定义剪裁区域(左上角和右下角坐标)  
    //cv::Rect roi(x, y, width, height); // x, y 是剪裁区域的左上角坐标,width, height 是剪裁区域的宽度和高度  

    int centerX = 1900;
    int centerY = 1800;
    int cropWidth = 1900;
    int cropHeight = 1450;
    cv::Rect roi(centerX - cropWidth / 2, centerY - cropHeight / 2, cropWidth, cropHeight);
    // 使用ROI剪裁图像  
    cv::Mat croppedImage = src(roi);
    cv::imwrite("C:/Users/yzy/Desktop/img/gaos_1.bmp", croppedImage);
    return std::make_pair(croppedImage, src);
}
std::pair<cv::Mat, cv::Mat> cuttingImage()
{
    cv::Mat src = cv::imread("C:/Users/yzy/Desktop/img/gaos_1.bmp");
    if (src.empty())
    {
        std::cerr << "Could not open or find the image!" << std::endl;
        return std::make_pair(cv::Mat(), cv::Mat());;
    }
    Mat img = imread("C:/Users/yzy/Desktop/img/gaos_1.bmp");
    Mat grayImage;
    cvtColor(img, grayImage, COLOR_BGR2GRAY);
    int ksize = 5;
    GaussianBlur(grayImage, grayImage, cv::Size(ksize, ksize), 0);
    imshow("gauss", grayImage);
    Mat contrastEnhancedEdges;
    equalizeHist(grayImage, contrastEnhancedEdges);
    double lowThreshold = 50;
    double highThreshold = 150;
    Mat edges;
    Canny(contrastEnhancedEdges, edges, lowThreshold, highThreshold);
    vector<Vec3f> circles;
    HoughCircles(edges, circles, HOUGH_GRADIENT, 1, grayImage.rows / 8, 200, 80, 0, 0);
    Mat croppedImg;
    if (!circles.empty())
    {
        // 获取最大圆的中心点和半径  
        Point center(cvRound(circles[0][0]), cvRound(circles[0][1]));
        int radius = cvRound(circles[0][2]);

        // 检查圆是否完全在图像内部  
        if (isCircleInsideImage(center, radius, img))
        {
            cout << "The largest circle in the photo" << endl;

            // 计算圆形ROI的左上角和右下角坐标  
            Rect roi(center.x - radius, center.y - radius, 2 * radius, 2 * radius);

            // 确保ROI在图像边界内  
            roi &= Rect(0, 0, img.cols, img.rows);

            // 提取ROI  
            croppedImg = img(roi);

            // 保存剪切后的图像  
            cv::imwrite("C:/Users/yzy/Desktop/img/gaos_3.bmp", croppedImg);
        }
    }
    return std::make_pair(croppedImg, img);
}
std::pair<cv::Mat, cv::Mat> outlineImage() {
    //按比例提取
    Mat out_one = imread("C:/Users/yzy/Desktop/img/gaos_3.bmp");
    Mat grayImage(out_one.size(), CV_8UC1);
    for (int y = 0; y < out_one.rows; ++y) {
        for (int x = 0; x < out_one.cols; ++x) {
            cv::Vec3b pixel = out_one.at<cv::Vec3b>(y, x);
            uchar B = pixel[0];
            uchar G = pixel[1];
            uchar R = pixel[2];
            float grayValue = 0.072169f * B + 0.715160f * G + 0.212671f * R;
            grayImage.at<uchar>(y, x) = static_cast<uchar>(std::min(255.0f, std::max(0.0f, grayValue)));
        }
    }
    //边缘检测
    cv::Mat edges;
    cv::Canny(grayImage, edges, 50, 150);
    // 转换为二值图像
    Mat binary_image;
    cv::imshow("C:/Users/yzy/Desktop/img/gaos_10.bmp", edges);
    threshold(edges, binary_image, 200, 255, THRESH_BINARY);
    
    std::vector<cv::Vec2f> lines;
    cv::HoughLines(binary_image, lines, 10, CV_PI / 10, 50); // 参数可能需要调整以适应你的图像  

    // 绘制检测到的直线  
    cv::Mat line_Image = out_one.clone();
    for (size_t i = 0; i < lines.size(); i++) {
        float rho = lines[i][0];
        float theta = lines[i][1];
        double a = cos(theta);
        double b = sin(theta);
        double x0 = a * rho;
        double y0 = b * rho;
        cv::Point pt1(cvRound(x0 + 1000 * (-b)), cvRound(y0 + 1000 * (a)));
        cv::Point pt2(cvRound(x0 - 1000 * (-b)), cvRound(y0 - 1000 * (a)));
        cv::line(line_Image, pt1, pt2, cv::Scalar(0, 0, 255), 2);
    }

    // 显示结果  
    cv::imshow("Detected Lines", line_Image);

    Mat drawImage = Mat::zeros(out_one.size(), out_one.type());
    std::vector<std::vector<cv::Point>> contours;
    std::vector<cv::Vec4i> hierarchy;
    cv::findContours(edges, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
    std::vector<std::vector<cv::Point>> filteredContours;
    for (const auto& contour : contours) {
        double contourArea = cv::contourArea(contour);
        if (contourArea >= 5) {
            filteredContours.push_back(contour);
        }
    }


    // 在原图上绘制过滤后的轮廓  
    cv::Mat resultImage = out_one.clone();
    cv::drawContours(resultImage, filteredContours, -1, cv::Scalar(0, 255, 0), 2);
    cv::imshow("luok",resultImage);
    cv::imwrite("C:/Users/yzy/Desktop/img/gaos_9.bmp", resultImage);
    
    return std::make_pair(edges, out_one);

}




int main()
{
    //std::pair<cv::Mat, cv::Mat> result = cropImage();
    //std::pair<cv::Mat, cv::Mat> result1 = cuttingImage();
    std::pair<cv::Mat, cv::Mat> result2 = outlineImage();

    waitKey(0);

    return 0;
}
import cv2 as cv
import cv2
import numpy as np
import time
from matplotlib import pyplot as plt

value = 60
value1 = 0
canny_min = 100
canny_max = 150
minlineLength = 200
maxlineGap = 10
area_threshold = 90


#用于去除杂点
def removeLittlePoint(img,threshold):
    image, contours, hierarch = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    for i in range(len(contours)):
        area = cv2.contourArea(contours[i])
        if area < threshold:
            cv2.drawContours(image, [contours[i]], 0, 0, cv2.FILLED)
    return image


def callback(object):
    global value,value1,src2,src2_copy,src,minlineLength,maxlineGap,canny_max,canny_min,area_threshold
    src2[:,:] = src2_copy[:,:]
    #得到滑动条对应的值

    src = cv2.bilateralFilter(src2, 11, value, value1)

    cv2.imshow("src", src)
    src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    roi = cv2.adaptiveThreshold(src, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \
                                cv2.THRESH_BINARY, 11, 3)
    mask = np.ones((3, 1), np.uint8)
    roi = cv2.morphologyEx(roi, cv2.MORPH_OPEN, mask, iterations=2)
    roi = cv2.bitwise_not(roi)

    roi = cv2.medianBlur(roi, 3,)
    cv2.imshow('roi', roi)
    roi_all = cv2.resize(roi, (round(roi.shape[1]/6), round(roi.shape[0]/6)))
    cv2.imshow('roi_all', roi_all)

    roi_canny = cv2.Canny(roi, canny_min, canny_max)
    roi_canny = cv2.resize(roi_canny, (round(roi_canny.shape[1] ), round(roi_canny.shape[0] )))
    cv2.imshow('roi_gray', roi_canny)

    oshow = roi_canny.copy()
    oshow = cv2.cvtColor(roi_canny, cv2.COLOR_GRAY2BGR)
    draw = np.zeros((roi_canny.shape[0],roi_canny.shape[1]), dtype=np.uint8)
    #霍夫直线检测,并绘出
    lines = cv2.HoughLines(roi_canny, 1, np.pi / 180, 1000)
    print(len(lines))
    for line in lines:
        rho, theta = line[0]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 10000 * (-b))
        y1 = int(y0 + 10000 * (a))
        x2 = int(x0 - 10000 * (-b))
        y2 = int(y0 - 10000 * (a))
        cv2.line(oshow, (x1, y1), (x2, y2), (0, 0, 255), 6,cv2.LINE_AA)
        cv2.line(draw, (x1, y1), (x2, y2), 255, 6, cv2.LINE_AA)
    oshow1 = cv2.resize(oshow, (round(oshow.shape[1] / 6), round(oshow.shape[0] / 6)))
    cv2.imshow('oshow', oshow1)

    kernel = np.ones((3, 3), np.uint8)
    dilation = cv2.dilate(oshow, kernel, iterations=6)
    draw = cv2.dilate(draw, kernel, iterations=6)
    dilation_all = cv2.resize(dilation, (round(dilation.shape[1] / 6), round(dilation.shape[0] / 6)))
    cv2.imshow('dilation_all', dilation_all)
    cv2.imshow('dilation', dilation)
    cv2.imshow('draw', draw)
    output = cv2.bitwise_and(draw, roi)
    result = roi[:, :] - output[:, :]
    output1 = cv2.resize(output, (round(output.shape[1]/6), round(output.shape[0]/6)))
    cv2.imshow('output', output1)
    result1 = cv2.resize(result, (round(result.shape[1]/6), round(result.shape[0]/6)))
    cv2.imshow('result', result1)

    new_result = removeLittlePoint(result, area_threshold)
    new_result1 = cv2.resize(new_result, (round(new_result.shape[1] / 6), round(new_result.shape[0] / 6)))
    cv2.imshow('new_result1', new_result1)


dianpianwrong = cv.imread("C:/Users/yzy/Desktop/img/pp.jpg")


src2 = dianpianwrong.copy()
dianpianwrong = cv2.resize(dianpianwrong, (round(dianpianwrong.shape[1]/6 ), round(dianpianwrong.shape[0]/6 )))
print("src.shape", src2.shape)
cv2.imshow("origon-picture", dianpianwrong)


src2_copy = np.zeros((src2.shape[0], src2.shape[1],3), np.uint8)
src2_copy[:, :] = src2[:, :]



有一点点迷茫,什么样才叫学会C++,是四大法宝都会还是能复现项目,能加功能。写一道比较基础的题,突然发现我的第一反应是去搜一下。经验和经历都有欠缺。

然后就是都是去处理缺陷检测的,但是都没写完,python的个人感觉不到快乐,图片太大。python自动死机,真心话

不要学python,不要学python,先去啃C++,,python 是没有活路的。明天把这个搞完,谁有halcon的安装教程,不要太智障的那种。现在好多的都好呆。,就这,就这了

小垃圾了我。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值