如何根据蒙版阈值裁剪图像?

How to crop images based on mask threshold?

我必须手动裁剪很多图像。这不是最有趣的事情。所以我想我会尝试使用 Python.

我可以检测主体,创建蒙版,但我不知道如何从最底部获取点并根据它们进行裁剪。

感谢任何帮助

import cv2

img = cv2.imread('image5.jpg')
h, w = img.shape[:2]

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


thr = cv2.threshold(gray, 192, 255, cv2.THRESH_BINARY_INV)[1]
cv2.imwrite('result5.png', thr)

我想说的非常好!现在实施:

xx,yy = thrs.nonzero()
max_crop_h = xx.max()
crop = img[:max_crop_h,:]

numpy 支持你!

您可以尝试使用 cv2.RETR_EXTERNAL 找到所有外部轮廓并选择最底部的点,如下所示:

import cv2
import numpy as np
import imutils

im = cv2.imread('images/tennis.jpg')

# Percent of original size
scale_percent = 20 
width = int(im.shape[1] * scale_percent / 100)
height = int(im.shape[0] * scale_percent / 100)
dim = (width, height)
  
# Resize image
im = cv2.resize(im, dim, interpolation = cv2.INTER_AREA)

# Convert to grayscale
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

# Canny
canny_output = cv2.Canny(im, 120, 240)

# Find external contours
contours, hierarchy = cv2.findContours(canny_output, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#cv2.drawContours(im, [contours[0]], 0, (0,255,0), 3) # Uncomment this line to see what contour opencv is finding

# Pick the bottom most point and add an offset (whatever value you want, this is just for aesthetics)
c = contours[0]
bottommost = tuple(c[c[:, :, 1].argmax()][0])[1] + 5

# Crop image
im = im[:bottommost, :]

# Show image
cv2.imshow('image', im)
cv2.waitKey()