簡體   English   中英

Python-圖片上單一顏色的矩形輪廓

[英]Python -Rectangular Contour on a single color on image

我正在嘗試在綠色圖像周圍繪制矩形輪廓

我能夠繪制最大的矩形,但無法專門繪制單色。

任何幫助都會很棒。

需要輪廓的圖像

預期結果是將明亮的綠色部分裁剪為矩形圖像。

我的代碼是-:

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創建一個遮罩,該遮罩可容納亮綠色區域。 接下來,選擇最大輪廓,即屏幕。 然后使用輪廓的boundingRect創建新圖像。

結果:
在此處輸入圖片說明

碼:

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()

通常,您可以通過將圖像中的對象轉換為不同的色彩空間,然后拆分各個通道以查看最能區分顏色的方法,來很好地了解它們。 因此,如果對圖像執行此操作,則會得到以下信息:

在此處輸入圖片說明

  • 第一行是Lab色彩空間中的圖像,左側是“亮度”,然后 a ,然后 b

  • 第二行是HSL色彩空間,左側是“ 色相 ”,然后是“ 飽和度” ,然后是“ 亮度”

隨后的行是YIQXYZRGB

您可以使用cvtColor()OpenCV中獲得它們的每一個。

現在,您查看圖像,看看將使您的LCD顯示屏與眾不同。

  • 綠色看起來不錯,但包括LCD左側上方的黃色
  • 同樣的亮度
  • 飽和度看起來不錯,但還包括圖像的右下角

它看起來像一個第三行中的頂行和Q可能是很好的,你會在兩種情況下閾值,以獲得暗色調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM