opencv 如何在logo周围画一个矩形?

qltillow  于 2022-12-13  发布在  Go
关注(0)|答案(1)|浏览(116)

我有一个小问题。source image有一个标志,我必须检测,使矩形围绕它。
我写了一些代码:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('9.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(img, (3, 3), 0)
_, binary = cv2.threshold(blur, 100, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C)

plt.imshow(binary, cmap='gray')
plt.show()

而得到了这样的结果:现在我不知道如何在它周围画一个矩形

a1o7rhls

a1o7rhls1#

具体操作如下:

img = cv2.imread('img.png')

temp = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, temp = cv2.threshold(temp, thresh=0, maxval=255, type=cv2.THRESH_BINARY + cv2.THRESH_OTSU)

kernel = np.ones((5, 5), np.uint8)
temp = cv2.dilate(temp, kernel, iterations=1)

contours, hierarchy = cv2.findContours(temp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
x, y, w, h = cv2.boundingRect(contours[0])

# draw a rectangle around the image
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)

相关问题