日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python?opencv實現目標外接圖形_python

作者:DanCheng-studio ? 更新時間: 2022-09-26 編程語言

本文實例為大家分享了python opencv實現圖像目標的外接圖形,供大家參考,具體內容如下

當使用cv2.findContours函數找到圖像中的目標后,我們通常希望使用一個集合區域將圖像包圍起來,這里介紹opencv幾種幾何包圍圖形。

  • 邊界矩形
  • 最小外接矩形
  • 最小外接圓

簡介

無論使用哪種幾何外接方法,都需要先進行輪廓檢測。

當我們得到輪廓對象后,可以使用boundingRect()得到包裹此輪廓的最小正矩形,minAreaRect()得到包裹輪廓的最小矩形(允許矩陣傾斜),minEnclosingCircle()得到包裹此輪廓的最小圓形。

最小正矩形和最小外接矩形的區別如下圖所示:

實現

這里給出上述5中外接圖形在python opencv上的實現:

①. 邊界矩形

import cv2
import numpy as np

img = cv2.imread('/home/pzs/圖片/test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh, binary = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV)
binary, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cv2.imshow('binary', binary)
cv2.waitKey(0)

for cnt in contours:
? ? x,y,w,h = cv2.boundingRect(cnt)
? ? cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 1)

cv2.imshow('image', img)
cv2.waitKey(0)

②. 最小外接矩形

import cv2
import numpy as np

img = cv2.imread('/home/pzs/圖片/test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh, binary = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV)
binary, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cv2.imshow('binary', binary)
cv2.waitKey(0)

for cnt in contours:
? ? rect = cv2.minAreaRect(cnt)
? ? box = cv2.boxPoints(rect)
? ? box = np.int0(box)
? ? cv2.drawContours(img, [box], 0, (0, 0, 255), 2)


cv2.imshow('image', img)
cv2.waitKey(0)

③. 最小外接圓

import cv2
import numpy as np

img = cv2.imread('/home/pzs/圖片/test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh, binary = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV)
binary, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cv2.imshow('binary', binary)
cv2.waitKey(0)

for cnt in contours:
? ? (x, y), radius = cv2.minEnclosingCircle(cnt)
? ? center = (int(x), int(y))
? ? radius = int(radius)
? ? cv2.circle(img, center, radius, (255, 0, 0), 2)

cv2.imshow('image', img)
cv2.waitKey(0)

原文鏈接:https://blog.csdn.net/HUXINY/article/details/89329307

欄目分類
最近更新