我正在做我的第一个opencv和python项目,但我遇到了麻烦。 关键是,我需要确定角落中的四个正方形,然后旋转图像,以便它们对齐。
起初,我尝试使用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()
然后,我想到了查找连接的组件的方法,但是找到之后,我无法确定正方形。第二个代码,与第一个非常相似:
import cv2 as cv
import numpy as np
# abre imagem e limiariza 0 = passar pra b&w
im = cv.imread('DQ.jpg', 0)
rett, im_bi = cv.threshold(im, 0, 255, cv.THRESH_OTSU)
# calcula tamanhos da imagem
tam = np.shape(im)
A = round(tam[0] * 0.2)
L = round(tam[1] * 0.2)
# calcula negativo da imagem
neg = cv.bitwise_not(im_bi)
# mostra imagem negativa
cv.namedWindow("negativa", cv.WINDOW_NORMAL) # permite que alteremos o tamanho da janela
cv.imshow('negativa', neg)
cv.resizeWindow('negativa', L, A) # altera o tamanho da janela
cv.waitKey(0)
cv.destroyAllWindows()
# encontra os componentes conexos da imagem
connectivity = 8
ret, labels = cv.connectedComponents(neg, connectivity, cv.CV_32S)
# normaliza os rótulos para tons de cinza
label_hue = np.uint8(179*labels/np.max(labels))
cv.namedWindow("labeled", cv.WINDOW_NORMAL)
cv.imshow('labeled', label_hue)
cv.resizeWindow('labeled', L, A)
cv.waitKey(0)
cv.destroyAllWindows()
# colors the labeled image, just for show
# blank_ch = 255*np.ones_like(label_hue)
# rot_im = cv.merge([label_hue, blank_ch, blank_ch])
# rot_im = cv.cvtColor(rot_im, cv.COLOR_HSV2BGR)
# rot_im[label_hue == 0] = 0
# cv.namedWindow("final", cv.WINDOW_NORMAL)
# cv.imshow('final', rot_im)
# cv.resizeWindow('final', L, A)
# cv.waitKey(0)
# cv.destroyAllWindows()
评论用葡萄牙语撰写,但并不复杂,正如您所看到的,我只想在对他们进行某些操作后显示所有图像哈哈。我想知道以上其中一项对我的项目会更好。我本人更愿意使用connectedComponents,因为我更好地了解了它对图像的作用,但是我发现所有类似的教程都使用findContours。 除此之外,我该怎么办?非常感谢!