DanBloomberg / leptonica

Leptonica is an open source library containing software that is broadly useful for image processing and image analysis applications. The official github repository for Leptonica is: danbloomberg/leptonica. See leptonica.org for more documentation.
Other
1.74k stars 387 forks source link

I need to copy the red marked area from the following figure. How do I do it #669

Open jueqing1015 opened 1 year ago

jueqing1015 commented 1 year ago

008

DanBloomberg commented 1 year ago

I'd suggest filtering for the red pixels, finding the bounding box of those red pixels, and cropping it out.

A simple way to do this is: Pix pix1 = pixRead() Pix pix2 = pixMaskOverColorPixels(pix1, 50, 1); // filter for red pixels Box box1; pixClipToForeground(pix2, NULL, &box1); // get bounding box of red pixels Pix pix3 = pixClipRectangle(pix1, box1, NULL); // extract that region from input image

jueqing1015 commented 1 year ago

@DanBloomberg How to remove the noise in the picture above? I have tried other methods to remove it

DanBloomberg commented 1 year ago

The image is grayscale. The noise has the characteristic that it is small but black, so thresholding will not help.

Because the noise is small you might think to use morphological filtering. That is a viable approach. However, because the text has thin regions, it would need to be done carefully, and with reconstructive seed-filling into connected components after removal of the noise. See prog/italic_reg.c for how this is done.

Another approach is to locate the connected components and filter out the small ones. This is simple.

Pix *pix4 = pixConvertTo1(pix3, 128);   // convert to 1 bpp
Pix *pix5 = pixSelectBySize(pix4, 2, 2, 8, L_SELECT_IF_EITHER, L_SELECT_IF_GT, 0);  // remove small noise

If you want to also remove the outline from the original red box, do this:

Pix *pix4 = pixConvertTo1(pix3, 128);   // convert to 1 bpp
pixSetOrClearBorder(pix4, 3, 3, 3, 3, PIX_CLR);   // clear the pixels within 3 from the border
Pix *pix5 = pixSelectBySize(pix4, 2, 2, 8, L_SELECT_IF_EITHER, L_SELECT_IF_GT, 0);  // remove small noise

Putting it all together:

Pix *pix1 = pixRead(<your input image>)
Pix *pix2 = pixMaskOverColorPixels(pix1, 50, 1); // filter for red pixels
Box *box1;
pixClipToForeground(pix2, NULL, &box1); // get bounding box of red pixels
Pix *pix3 = pixClipRectangle(pix1, box1, NULL); // extract that region from input image
Pix *pix4 = pixConvertTo1(pix3, 128);    // convert from rgb to 1 bpp
pixSetOrClearBorder(pix4, 3, 3, 3, 3, PIX_CLR);   // clear the pixels within 3 from the border
Pix *pix5 = pixSelectBySize(pix4, 2, 2, 8, L_SELECT_IF_EITHER, L_SELECT_IF_GT, 0);  // remove small noise

Note that the text is much thinner than the original you show above. However, the thinning occurred when I saved your image from github. It was not done by leptonica.

pix5

DanBloomberg commented 1 year ago

here's the result with the border from the red pixels removed:

pix5