使用卡片的宽度,高度或颜色检测并裁剪具有多个对象的图像中的卡片 [英] Detect and crop card in image with multiple objects using width and height or color of card

查看:75
本文介绍了使用卡片的宽度,高度或颜色检测并裁剪具有多个对象的图像中的卡片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一张图像中有一张包含多个对象的卡片,我想使用卡片的宽度,高度或颜色来剪裁卡片.

I have a card with multiple objects in one image and I want to crop the card using width and height or color of the card.

我可以使用以下代码进行裁剪:

I can crop using code below:

import cv2
img = cv2.imread('/Users/akram/Downloads/img.jpg', 1)
x = 0
y = 0
width = 500
height = 500
cropped_img = img[y:y+height, x:x+width]
cv2.imshow("cropped_images", cropped_img)
cv2.waitKey(0)

但是当我有其他图像宽度卡时, width = 500 and height = 500 x = 200 y = 100

But when I have other image width card width = 500 and height = 500 and x = 200 y = 100

我需要使用 x = 200和y = 100 编辑我的代码.

I need to edit my code with x = 200 and y = 100.

问题是我一直都不知道卡的位置,因此我需要创建一个动态代码来裁剪图像中位置为x或y的卡.

The problem is that I don't know the position of the card in all time, so I need to create a dynamic code to crop the card with any position x or y in image.

我不知道如何实现此目的,我是OpenCV的新手,而计算机视觉实际上是该领域的新手.

I don't know how can I achieve this purpose, I'm new in OpenCV and computer vision in fact I'm new in this domain.

示例图片

任何人都可以帮助我解决此问题,谢谢?

Anyone can help me to resolve this issue and thanks ?

推荐答案

正如Elyas Karimi所指出的,您可以通过找到轮廓来检测卡片.一种方法是找到输入图像的最大边界框,然后根据该边界框进行裁剪.对于示例图像,您将通过这种方式获得ID卡.

As Elyas Karimi pointed out, you can detect the card by finding contours. One way to do it is to find the biggest bounding box for the input image and then crop according to that bounding box. For the sample image, you'd get the ID card this way.

这是一个示例实现:

#!/usr/bin/env python

import cv2
import numpy as np

# load image
img = cv2.imread('Image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert to grayscale
# threshold to get just the signature (INVERTED)
retval, thresh_gray = cv2.threshold(gray, thresh=245, maxval=255, \
                                   type=cv2.THRESH_BINARY_INV)
cv2.imwrite('Image_gray.jpg', thresh_gray)  # debugging

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

# Crop and save
roi=img[y:y+h,x:x+w]
cv2.imwrite('Image_crop.jpg', roi)

# Draw bounding box rectangle (debugging)
cv2.rectangle(img,(x,y),(x+w,y+h),(200,0,0),2)
cv2.imwrite('Image_cont.jpg', img)

您还可以在检测到的卡下找到最大的边界框以获取签名(或为此使用层次结构).

You could also find the biggest bounding box under the detected card to get the signature as well (or use hierarchy for this purpose).

输入图片:

边界框:

作物:

这篇关于使用卡片的宽度,高度或颜色检测并裁剪具有多个对象的图像中的卡片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆