python - 我想使用openCv从图像中删除模糊的黑色边框-LMLPHP

我想从该图像上去除黑色边框,以便在打印时不会用完墨粉。

我尝试了以下过程,但它删除了整个图像:

#Remove Black Borders from images
img = cv2.imread("images/myimage.jpg")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_,thresh = cv2.threshold(gray,10,256,cv2.THRESH_BINARY)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)
crop = img[y:y+h,x:x+w]
cv2.imwrite('images/crop.png',crop)

有什么线索吗?

最佳答案

如果均值小于100,则可以尝试获取垂直和水平线的平均值,将黑色变为白色:

import cv2
import numpy as np

img=cv2.imread("test.jpg",0).T #load image and transpose it(like rotate 90 degree)
sens=1.0 # (0-1]
meanofimg=np.mean(img)*sens #get avarage brightness of img
w,h=img.shape #get image's shape
for i in range(w): #for every horizontal line in transposed img(vertical line in normal)
    if np.mean(img[i])<meanofimg: #check if this line darker than avarage
        img[i]=(img[i]+255)%256 #add 255 for every pixel and get mod 256 this for make zeros 255 and do not touch others
        #img[i]=(img[i]*0+255) #for makin all pixels in line white
img=img.T #turn image to normal
for i in range(h): #every horizontal line in img
    if np.mean(img[i])<meanofimg: # if line darker than avarage
        img[i]=(img[i]+255)%256 #do same thing
        #img[i]=(img[i]*0+255) #for makin all pixels in line white

cv2.imwrite("output.jpg",img) #write img as output.jpg

用于裁剪img:
import cv2
import numpy as np

img=cv2.imread("test.jpg",0).T
w,h=img.shape
sens=1.0 # (0-1]
meanofimg=np.mean(img)*sens
dataw=[w,0]
datah=[h,0]
for i in range(w):
    if np.mean(img[i])>meanofimg:
        if i<dataw[0]:
            dataw[0]=i
        else:
            dataw[1]=i
img=img.T
meanofimg=np.mean(img)*sens
for i in range(h):
    if np.mean(img[i])>meanofimg:
        if i<datah[0]:
            datah[0]=i
        else:
            datah[1]=i
img=img[datah[0]:datah[1],dataw[0]:dataw[1]]
cv2.imwrite("output.jpg",img)

关于python - 我想使用openCv从图像中删除模糊的黑色边框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54888690/

10-12 16:39