首页 文章

裁剪图像python的边框

提问于
浏览
0

我有这张照片

我想像这样裁剪它

我使用此代码,但它不会裁剪黑色边框 . 所以,有人可以帮助我吗?

im = cv2.imread("Data/"+file, 0)
    retval, thresh_gray = cv2.threshold(im, thresh=100, maxval=255, type=cv2.THRESH_BINARY)
    points = np.argwhere(thresh_gray==0)
    points = np.fliplr(points)
    x, y, w, h = cv2.boundingRect(points)
    crop = im[y:y+h, x:x+w] # create a crop
    retval, thresh_crop = cv2.threshold(crop, thresh=200, maxval=255, type=cv2.THRESH_BINARY)
    path = 'D:\Picture\Camera Roll'
    cv2.imwrite(os.path.join(path , file),thresh_crop)

1 回答

  • 0

    我认为您可以使用contours作为解决方案 . 轮廓是连接相同强度的连续点的曲线/线 . 因此,包含书面脚本的框是一个轮廓 . 图像中的轮廓也具有关系,例如一个轮廓可以是其他轮廓的父级 . 在您的图像中,该框可以是书面脚本的父级 .

    cv2.findContours查找图像中的所有轮廓,第二个参数(cv2.RETR_TREE)是指应返回哪种关系 . 由于轮廓具有层次结构,因此框可能位于轮廓列表的索引0或1中 .

    import matplotlib.pyplot as plt
    %matplotlib inline
    img = cv2.imread('image.png', 0)
    ret, thresh = cv2.threshold(img, 127, 255, 0)
    image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    

    我虽然第一个轮廓(轮廓[0])代表方框,但由于某种原因它是第二个轮廓 .

    img_copy = img.copy()
    cnt= contours[1]
    cv2.drawContours(img_copy, [cnt], -1, color = (255, 255, 255), thickness = 20)
    plt.imshow(img_copy, 'gray')
    

    在获得轮廓后,只需在轮廓上画一条粗白线就可以取下盒子 . 这是一个solution来绘制图像上的特定轮廓

    不要担心这些图像中的边界框 . 它只是matplotlib . 您的图像是坐标框内的图像 .

相关问题