我可以使用连接组件或findContents来识别方块吗?在python上使用opencv

2024-05-15 21:46:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做我的第一个opencv和python项目,但是我被卡住了。 问题是,我需要确定四个正方形的角,然后旋转图像,使它们对齐。在

(Image DG.jpg)

一开始我试着用findContours,但当我尝试绘制轮廓时,它似乎不起作用。代码如下:

import cv2 as cv
import numpy as np

# ler a imagem
im = cv.imread('DQ.jpg', 0)
rett, im_bi = cv.threshold(im, 0, 255, cv.THRESH_OTSU)

# definir dimensões da imagem
tam = np.shape(im)
print(tam)
A = round(tam[0] * 0.3)
L = round(tam[1] * 0.3)

# canny edges
edge = cv.Canny(im_bi, 30, 200)
cv.namedWindow('Canny edges', cv.WINDOW_NORMAL)
cv.imshow('Canny edges', edge)
cv.resizeWindow('Canny edges', L, A)
cv.waitKey(0)

contours, contours, hierarchy = cv.findContours(edge, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)  # how to fix??
cv.namedWindow('findContours', cv.WINDOW_NORMAL)
cv.imshow('findContours', edge)
cv.resizeWindow('findContours', L, A)
cv.waitKey(0)

cv.drawContours(im_bi, contours, -1, (0,255,39), 3)

cv.namedWindow('drawContours', cv.WINDOW_NORMAL)
cv.imshow('drawContours', im_bi)
cv.resizeWindow('drawContours', L, A)
cv.waitKey(0)

cv.destroyAllWindows()

然后我想找到它的连接部分,但找到之后,我就无法识别正方形了。第二个代码与第一个代码非常相似:

^{pr2}$

评论是葡萄牙语的,但并不像你看到的那样复杂,我只是想在我对他们做了一些事情之后把所有的图片都展示出来。我想知道以上哪一种更适合我的项目。我自己更愿意使用connectedComponents,因为我更了解它对图像的作用,但是我发现的所有类似教程都使用findContours。 除此之外,我以后该怎么办?谢谢!在


Tags: 代码windowcvnormalbiimshowedgeim