使用python进行图像卡检测

时间:2018-07-18 11:03:08

标签: python python-3.x image-processing python-imaging-library python-imageio

我想使用python检测这张图片中有多少张卡片。我尝试使用白色像素,但未获得正确的结果。enter image description here

我的代码如下:

import cv2
import numpy as np

img = cv2.imread('imaagi.jpg', cv2.IMREAD_GRAYSCALE)
n_white_pix = np.sum(img == 255)
print('Number of white pixels:', n_white_pix)

我是初学者。因此无法找出方法。

2 个答案:

答案 0 :(得分:2)

此解决方案针对您提供的图像,并且在OpenCV中实现。

代码:

im = cv2.imread('C:/Users/Jackson/Desktop/cards.jpg', 1)

#--- convert the image to HSV color space ---
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
cv2.imshow('H', hsv[:,:,0])
cv2.imshow('S', hsv[:,:,1])

#--- find Otsu threshold on hue and saturation channel ---
ret, thresh_H = cv2.threshold(hsv[:,:,0], 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
ret, thresh_S = cv2.threshold(hsv[:,:,1], 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

#--- add the result of the above two ---
cv2.imshow('thresh', thresh_H + thresh_S)

#--- some morphology operation to clear unwanted spots ---
kernel = np.ones((5, 5), np.uint8)
dilation = cv2.dilate(thresh_H + thresh_S, kernel, iterations = 1)
cv2.imshow('dilation', dilation)

#--- find contours on the result above ---
(_, contours, hierarchy) = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

#--- since there were few small contours found, retain those above a certain area ---
im2 = im.copy()
count = 0
for c in contours:
    if cv2.contourArea(c) > 500:
        count+=1
        cv2.drawContours(im2, [c], -1, (0, 255, 0), 2)

cv2.imshow('cards_output', im2)
print('There are {} cards'.format(count))

结果:

在终端上,我得到了There are 6 cards

enter image description here

答案 1 :(得分:0)

根据“白色像素方法”的工作原理(如果可能,请分享更多详细信息),您可以尝试使用简单的image binarization,这是一种将不同对象/实体分开的公认方法在您的图像中。当然,它仅适用于灰度图像,但是您也可以使用sklearn轻松修复它。

它可能会立即提供最佳结果,尤其是在不同图像的光照条件不同或者您拥有(如上所示)卡片包含多种颜色的情况下。

要避免这种情况,您还可以尝试研究不同的颜色空间,例如HSV

如果仍然无法解决问题,我建议您使用OpenCV或similra库中的图像分割库。问题在于它们通常还会给您的项目带来一些不必要的复杂性,如果使用二进制化之类的简单方法,则可能不必要。