使用 OpenCV 和 python 在较大图像中裁剪灰度图像

Cropping greyscale images within larger images using OpenCV and python

嗨,我是 python 和 opencv 的新手。我有这张图片:

我正在尝试从图片中裁剪灰度图像。目前,代码会找到最大的边界框,即右上角的图像,然后对其进行裁剪。我想要做的是找到所有的灰度图像,即使图片中有超过 4 张,并将它们全部裁剪。我正在考虑使用循环来执行此操作,但我不想设置一个循环,它会找到最大的边界框 4 次然后停止,因为我正在处理的其他图像中会有超过 4 个图像。任何帮助将不胜感激!

import cv2
import numpy as np

# load image
img = cv2.imread('multi.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert to grayscale
# threshold to get just the signature (INVERTED)
retval, thresh_gray = cv2.threshold(gray, thresh=100, maxval=255, \
                                    type=cv2.THRESH_BINARY_INV)

image, contours, hierarchy = cv2.findContours(thresh_gray,cv2.RETR_LIST, \
                                              cv2.CHAIN_APPROX_SIMPLE)

# Find object with the biggest bounding box
mx = (0,0,0,0)      # biggest bounding box so far
mx_area = 0
for cont in contours:
    x,y,w,h = cv2.boundingRect(cont)
    area = w*h
    if area > mx_area:
        mx = x,y,w,h
        mx_area = area
x,y,w,h = mx

# Find object with the biggest bounding box

mx = (0,0,0,0)      # biggest bounding box so far
mx_area = 0
for cont in contours:
    x,y,w,h = cv2.boundingRect(cont)
    area = w*h
    if area > mx_area:
        mx = x,y,w,h
        mx_area = area
x,y,w,h = mx

# Output to files
roi=img[y:y+h,x:x+w]
cv2.imwrite('Image_crop.jpg', roi)

cv2.rectangle(img,(x,y),(x+w,y+h),(200,0,0),2)
cv2.imwrite('Image_cont.jpg', img)

我已经详细说明了我的评论。

在您提供的代码中,轮廓是使用 cv2.RETR_LIST 找到的,图像中的每个可能的轮廓,包括轮廓内出现的轮廓。我使用 cv2.RETR_EXTERNAL 忽略其他轮廓内的那些轮廓。

image = cv2.imread(r'C:\Users\Desktop\g.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

retval, thresh_gray = cv2.threshold(gray, thresh=100, maxval=255, \
                                    type=cv2.THRESH_BINARY_INV)
cv2.imshow('thresh_gray.png', thresh_gray)

image, contours, hierarchy = cv2.findContours(thresh_gray,cv2.RETR_EXTERNAL,                                                 cv2.CHAIN_APPROX_SIMPLE)

for i, c in enumerate(contours):
    if cv2.contourArea(c) > 10000:
        x, y, w, h = cv2.boundingRect(c)
        roi = image[y  :y + h, x : x + w ]

        cv2.imshow('Region_{}.jpg'.format(i), roi)
        cv2.waitKey(0)

cv2.destroyAllWindows()