gpt4 book ai didi

Python OpenCV 从二值图像中检测到一个白色物体并裁剪它

转载 作者:太空宇宙 更新时间:2023-11-03 11:51:51 25 4
gpt4 key购买 nike

我的目标是从这张二值图像中检测出一张白纸,然后裁剪这张白纸并为这张白纸制作一个新的子集二值图像。 enter image description here

现在我使用 OpenCV 的 Python 代码可以找到这篇白皮书。第一步,我创建了一个用于查找此白皮书的掩码: enter image description here

如你们所见,小白噪声和小片段已被移除。然后问题就变成了我如何从这个二值图像中裁剪这个白皮书对象来制作一个新的子集二值图像?

我当前的代码是:

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],0,255,-1)

找cnt var,有四个元素,但对我来说都是废话。我用代码来装盒子:

x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,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, hierarchy = cv2.findContours(QR,cv2.RETR_LIST,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,[cnt],0,255,-1) # the [] around cnt and 3rd argument 0 mean only the particular contour is drawn

# Build a ROI to crop the QR
x,y,w,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,y,w,h = cv2.boundingRect(cnt[best])
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

关于Python OpenCV 从二值图像中检测到一个白色物体并裁剪它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24897092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com