Search code examples
c++opencvcropedge-detectionimage-preprocessing

OpenCV Processing - Edge detection and Cropping


How do i remove the irregular white pixels from the preprocessed image.

i have tried doing erosion and that would make all pixels black.

After Preprocessing:

enter image description here

Requirement:

enter image description here

My Code:

Mat  img, edges, erode, blurred, element;
element = getStructuringElement(cv::MORPH_RECT, cv::Size(7, 7), cv::Point(-1,-1) ); 

img = imread("img1925.jpeg");    //  read the image
cv::Canny(img, edges, 30, 255, 3);    // detect the edges with threshold limit

//    cv::erode(edges, erode, element);

GaussianBlur(edges, blurred, cv::Size(7, 7), 0);    // blurring

//    Rect ROI = boundingRect(blurred);       // draw rect for ROI
//    Mat src = thresh(ROI);

namedWindow("image", WINDOW_NORMAL);
imshow("image", blurred);
waitKey(0);
return 0;

Looking for suggestions!


Solution

  • I'm not sure what you mean by removing the irregular white pixels from the preprocessed image but if your goal is to extract a ROI of the object then here's an approach:

    • Convert image to grayscale and Gaussian blur to smooth image
    • Adaptive threshold to obtain a binary image
    • Find contours and filter using contour area
    • Extract the largest contour in the image and crop the ROI

    Here's the result

    enter image description here

    If you cropped the ROI on the thresholded image, here's the result

    enter image description here

    I implemented it in Python but you can follow the same steps in C++

    import cv2
    
    image = cv2.imread('1.jpg')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (7,7), 0)
    thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,3)
    
    cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
    for c in cnts:
        x,y,w,h = cv2.boundingRect(c)
        ROI = image[y:y+h, x:x+w]
        break
    
    cv2.imwrite('ROI.png', ROI)
    cv2.waitKey()