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

时间:2018-06-08 11:29:44

标签: python numpy opencv image-processing crop

您好我是python和opencv的新手。我有这张图片:this

我试图从图片中裁剪灰度图像。此时,代码找到最大的边界框,即右上角的图像然后裁剪它。我想要做的是找到所有的灰度图像,即使图片中有超过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)

2 个答案:

答案 0 :(得分:2)

我已经阐述了我的评论。

在您提供的代码中,使用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()

答案 1 :(得分:0)

您的背景是否始终为绿色,并且您只有灰度图像? 如果是,那么我认为更好的方法是掩盖绿色(即找到像素为绿色的像素),现在您可以获得所有像素都是灰度的信息。如果没有,你可以使用hsv将其渲染出来,因为灰度图像的饱和度= 0且从0到100%的变化值 HSV

不要转换为灰度然后找到。 如果灰度图像的大小可变,则使用计数器区域的阈值将不起作用。