Home > Software design >  Unable to crop white background off a flatbed scan
Unable to crop white background off a flatbed scan

Time:09-09

I have scanned images of various products packagings as following enter image description here

These are in different sizes. I need to remove white background on right and under. I have tried several solutions but only enter image description here

CodePudding user response:

I didn't use the "opencv" library, I have used "skimage". After removing the white background, the resolution of the picture has been affected, I don't know if you can accept it. Here is the code:

from skimage import io
def corp_margin(img, threshold=600):
        img2=img.sum(axis=2)
        (row,col)=img2.shape
        row_top=0
        raw_down=0
        col_top=0
        col_down=0
        for r in range(0,row):
                if img2.sum(axis=1)[r]<threshold*col:
                        row_top=r
                        break
 
        for r in range(row-1,0,-1):
                if img2.sum(axis=1)[r]<threshold*col:
                        raw_down=r
                        break
 
        for c in range(0,col):
                if img2.sum(axis=0)[c]<threshold*row:
                        col_top=c
                        break
 
        for c in range(col-1,0,-1):
                if img2.sum(axis=0)[c]<threshold*row:
                        col_down=c
                        break
 
        new_img=img[row_top:raw_down 1,col_top:col_down 1,0:3]
        return new_img
image = io.imread("img.jpg")
img_re = corp_margin(image)
io.imshow(img_re)
io.imsave('new_image.jpg', img_re)

Here is the result I got : enter image description here

  • Related