gpt4 book ai didi

python - 如何使用 OpenCV 根据特定标准裁剪图像?

转载 作者:行者123 更新时间:2023-12-02 16:36:04 26 4
gpt4 key购买 nike

我想使用 python 的 OpenCV 库裁剪如下图所示的图像。感兴趣的区域位于顶部和底部的波浪线以及侧面的线内。问题是每个图像都略有不同。这意味着我需要一些自动裁剪感兴趣区域的方法。我猜顶部和侧面会很容易,因为您可以将其裁剪 10 像素左右。但是我怎样才能裁剪出线条不直的图像的下半部分呢?我已包含此示例图像。接下来的图像以粉红色突出显示我有兴趣保留的图像区域。

enter image description here

enter image description here

最佳答案

这是使用 Python/OpenCV 的一种方法。

  • 读取输入
  • 获取中心点(假设它在所需区域内)
  • 图像转灰度
  • 填充灰色图像并将背景设置为黑色
  • 获取最大轮廓及其边界框
  • 绘制黑色背景上填充的最大轮廓作为蒙版
  • 将蒙版应用于输入图像
  • 裁剪蒙版的输入图像

  • 输入:

    enter image description here
    import cv2
    import numpy as np

    # load image and get dimensions
    img = cv2.imread("odd_region.png")
    hh, ww, cc = img.shape

    # compute center of image (as integer)
    wc = ww//2
    hc = hh//2

    # create grayscale copy of input as basis of mask
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    # create zeros mask 2 pixels larger in each dimension
    zeros = np.zeros([hh + 2, ww + 2], np.uint8)

    # do floodfill at center of image as seed point
    ffimg = cv2.floodFill(gray, zeros, (wc,hc), (255), (0), (0), flags=8)[1]

    # set rest of ffimg to black
    ffimg[ffimg!=255] = 0

    # get contours, find largest and its bounding box
    contours = cv2.findContours(ffimg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours = contours[0] if len(contours) == 2 else contours[1]
    area_thresh = 0
    for cntr in contours:
    area = cv2.contourArea(cntr)
    if area > area_thresh:
    area = area_thresh
    outer_contour = cntr
    x,y,w,h = cv2.boundingRect(outer_contour)

    # draw the filled contour on a black image
    mask = np.full([hh,ww,cc], (0,0,0), np.uint8)
    cv2.drawContours(mask,[outer_contour],0,(255,255,255),thickness=cv2.FILLED)

    # mask the input
    masked_img = img.copy()
    masked_img[mask == 0] = 0
    #masked_img[mask != 0] = img[mask != 0]

    # crop the bounding box region of the masked img
    result = masked_img[y:y+h, x:x+w]

    # draw the contour outline on a copy of result
    result_outline = result.copy()
    cv2.drawContours(result_outline,[outer_contour],0,(0,0,255),thickness=1,offset=(-x,-y))


    # display it
    cv2.imshow("img", img)
    cv2.imshow("ffimg", ffimg)
    cv2.imshow("mask", mask)
    cv2.imshow("masked_img", masked_img)
    cv2.imshow("result", result)
    cv2.imshow("result_outline", result_outline)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # write result to disk
    cv2.imwrite("odd_region_cropped.png", result)
    cv2.imwrite("odd_region_cropped_outline.png", result_outline)

    结果:
    enter image description here

    绘制轮廓的结果:
    enter image description here

    关于python - 如何使用 OpenCV 根据特定标准裁剪图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59481977/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com