【问题标题】:how to cut image according to two points in opencv?如何在opencv中根据两点切割图像?
【发布时间】:2023-01-30 22:18:40
【问题描述】:

我有这个输入图像(请随意下载并尝试您的解决方案):

我需要找到最靠近左下角和右上角的点 A 和 B。而不是我想削减的形象。查看所需的输出:

到目前为止我有这个功能,但它没有正确找到点 A、B:


def CheckForLess(list1, val):
    return(all(x < val for x in list1))

def find_corner_pixels(img):
    # Get image dimensions
    height, width = img.shape[:2]

    # Find the first non-black pixel closest to the left-down and right-up corners
    nonempty = []


    for i in range(height):
        for j in range(width):
            # Check if the current pixel is non-black
            if not CheckForLess(img[i, j], 10):
                nonempty.append([i, 1080 - j])


    return min(nonempty) , max(nonempty)

你能帮我吗?

【问题讨论】:

  • 在此示例中,尝试使用定义范围的书籍颜色创建蒙版。然后使用 find_contour() 并获取边界
  • @AchilleG 我试过了,但它没有正确找到轮廓。也许我做错了什么,你能试试吗?
  • return min(nonempty) , max(nonempty) -> min() 不会在左下角找到你。代码必须找到最低的 y,它具有最低的 x 位置。不幸的是,这张图片中的“最低”点将具有较高的值,因为您的坐标十字可能位于左上角?

标签: python opencv


【解决方案1】:

我有点生疏,很久没有练习 opencv2 但这是我想出的:

import numpy as np
import cv2

img = cv2.imread("book.png")
timg = img.copy()

cv2.imshow("img", img)

# Get a mask to get only the colour you need (cover of the book)

hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower = np.array([10, 150, 150])

upper = np.array([35, 255, 255])

mask = cv2.inRange(hsv_img, lower, upper)

masked = cv2.bitwise_and(hsv_img, hsv_img, mask=mask)    

img[mask == 0] = 255


cv2.imshow("mask", img)

# Find contours of the masked image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# For some reason, first contour was the entire screen so only take the second rectangle
contours = sorted(contours, key=cv2.contourArea, reverse=True)[1:2]

for cnt in contours:
    x, y, w, h = cv2.boundingRect(cnt)
    
    # get the corners of the rectangle
    top_left = (x, y)
    top_right = (x + w, y)
    bottom_right = (x + w, y + h)
    bottom_left = (x, y + h)

height, width = img.shape[:2]

pt1 = (0, top_left[1]) 
pt2 = (width, top_left[1])
pt3 = (0, bottom_left[1]) 
pt4 = (width, bottom_left[1])
cv2.line(timg, pt1, pt2, [10, 150, 150],1 )
cv2.line(timg, pt3, pt4, [10, 150, 150], 1)

cv2.imshow("Bounding Rectangles", timg)

cv2.waitKey(0)

希望这有帮助(请注意,您只能通过获取轮廓的内容来检索这本书

然后,裁剪真的很容易

# Select the area to crop
cropped = img[y1:y2, x1:x2]

【讨论】:

    猜你喜欢
    • 2018-08-15
    • 2013-11-13
    • 1970-01-01
    • 2014-06-11
    • 2018-11-29
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多