我有一个小问题。源图像有一个标志,我必须检测和周围的矩形。
我写了一些代码:
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()
得到了这个结果:result现在我不知道如何在它周围画一个矩形
方法如下:
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)