Python OpenCV从二进制图像中检测白色对象并裁剪它

我的目标是从这个二进制图像中检测一张白纸然后裁剪这张白纸,并为这份白皮书制作一个新的子集二进制图像.

现在我的OpenCV Python代码可以找到这份白皮书.第一步,我创建了一个用于查找此白皮书的掩码:

正如你们所看到的,小的白噪声和小块已被删除.然后问题变成了如何从这个二进制图像中裁剪这个白皮书对象来制作一个新的子集二进制图像?

我目前的代码是:

import cv2
import numpy as np

QR = cv2.imread('IMG_0352.TIF',0) 
mask = np.zeros(QR.shape,np.uint8) 

contours,hierarchy = cv2.findContours(QR,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>1000000:
        cv2.drawContours(mask,[cnt],255,-1)

寻找cnt var,有四个元素,但它们对我来说是无稽之谈.
我使用代码来装箱:

x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0),2)

盒子信息似乎不正确.

谢谢你的任何建议.

跟进:
我已经弄清楚了这个问题,这很容易.代码附后:

import cv2
import numpy as np


QR_orig = cv2.imread('CamR_IMG_0352.TIF',0)
QR = cv2.imread('IMG_0352.TIF',0) # read the QR code binary image as grayscale image to make sure only one layer
mask = np.zeros(QR.shape,np.uint8) # mask image the final image without small pieces

# using findContours func to find the none-zero pieces
contours,cv2.CHAIN_APPROX_SIMPLE)

# draw the white paper and eliminate the small pieces (less than 1000000 px). This px count is the same as the QR code dectection
for cnt in contours:
    if cv2.contourArea(cnt)>1000000:
        cv2.drawContours(mask,-1) # the [] around cnt and 3rd argument 0 mean only the particular contour is drawn

        # Build a ROI to crop the QR
        x,h = cv2.boundingRect(cnt)
        roi=mask[y:y+h,x:x+w]
        # crop the original QR based on the ROI
        QR_crop = QR_orig[y:y+h,x:x+w]
        # use cropped mask image (roi) to get rid of all small pieces
        QR_final = QR_crop * (roi/255)

cv2.imwrite('QR_final.TIF',QR_final)

解决方法

轮廓对象是包围检测到的对象的点的任意向量(列表).

实现这一目标的一个简单的脑死亡方法是在阈值处理后遍历所有像素,然后简单地复制白色像素.

我相信findContours()会改变图像(副作用),所以检查QR.

但是,您需要(通常)获得最大的轮廓.
例:

# Choose largest contour
best = 0
maxsize = 0
count = 0
for cnt in contours:
    if cv2.contourArea(cnt) > maxsize :
        maxsize = cv2.contourArea(cnt)
        best = count

    count = count + 1

x,h = cv2.boundingRect(cnt[best])
cv2.rectangle(img,2)

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...