gpt4 book ai didi

Python - 图像上单一颜色的矩形轮廓

转载 作者:太空宇宙 更新时间:2023-11-03 21:59:09 24 4
gpt4 key购买 nike

我正在尝试围绕绿色图像绘制矩形轮廓

我能够画出最大的矩形,但无法专门用一种颜色画出。

任何帮助都会很棒。

Image which needs to be contoured over

预期的结果是裁剪出矩形的亮绿色部分的图像。

我的代码是 - :

import cv2
import numpy as np

median = cv2.imread("try.png", 0)
image_gray = median
image_gray = np.where(image_gray > 30, 255, image_gray)
image_gray = np.where(image_gray <= 30, 0, image_gray)
image_gray = cv2.adaptiveThreshold(image_gray, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 115, 1)
_, contours, _ = cv2.findContours(image_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rect_cnts = []
for cnt in contours:
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)
(x, y, w, h) = cv2.boundingRect(cnt)
ar = w / float(h)
if len(approx) == 4: # shape filtering condition
rect_cnts.append(cnt)
max_area = 0
football_square = None
for cnt in rect_cnts:
(x, y, w, h) = cv2.boundingRect(cnt)
if max_area < w*h:
max_area = w*h
football_square = cnt

# Draw the result
image = cv2.cvtColor(image_gray, cv2.COLOR_GRAY2RGB)
cv2.drawContours(image, [football_square], -1, (0, 0,255), 5)
cv2.imshow("Result Preview", image)
cv2.waitKey()

任何建议和帮助都可以帮助我仅在屏幕的矩形形状上绘制单一颜色的轮廓。

最佳答案

正如@MarkSetchell 所说,其他颜色空间可以使这更容易。例如,下面我将您的图像转换为 HSV。然后我使用 inRange 创建了一个包含亮绿色区域的 mask 。接下来选择最大的轮廓,即屏幕。然后使用轮廓的 boundingRect 创建新图像。

结果:
enter image description here

代码:

import numpy as np 
import cv2
# load image
image = cv2.imread('d3.jpg')
# create hsv
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# set lower and upper color limits
low_val = (60,180,160)
high_val = (179,255,255)
# Threshold the HSV image
mask = cv2.inRange(hsv, low_val,high_val)
# find contours in mask
ret, contours, hierarchy = cv2.findContours(mask,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# select the largest contour
largest_area = 0
for cnt in contours:
if cv2.contourArea(cnt) > largest_area:
cont = cnt
largest_area = cv2.contourArea(cnt)

# get the parameters of the boundingbox
x,y,w,h = cv2.boundingRect(cont)

# create and show subimage
roi = image[y:y+h, x:x+w]
cv2.imshow("Result", roi)

# draw box on original image and show image
cv2.rectangle(image, (x,y),(x+w,y+h), (0,0,255),2)
cv2.imshow("Image", image)

cv2.waitKey(0)
cv2.destroyAllWindows()

关于Python - 图像上单一颜色的矩形轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54605338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com