【问题标题】:how do I get the color that surrounds the Contour from outside, and how to fill the inside of a contour with a color?如何从外部获取轮廓周围的颜色,以及如何用颜色填充轮廓的内部?
【发布时间】:2021-11-26 07:32:33
【问题描述】:

我写了一个程序,将图片作为输入并检测写入的文本 我需要编辑我的程序以添加另外两个功能

首先 因为我已经能够获得轮廓坐标(完成),所以我想知道如何获得围绕每个字符轮廓线的背景颜色(在多个点,因为我想计算 RGB 颜色值的平均值围绕那个角色) 我只是不知道是否已经有一个功能可以做我想做的事情,或者是否有我应该遵循的特定方法

第二, 我试图填充轮廓的内部,但它没有用,有人可以帮我知道为什么 我确实在我的 cv2.drawContours 中尝试了厚度=-1 和厚度=cv2.FILLE,没有任何效果,显然只有控制线是蓝色的,但里面的不是蓝色

我知道代码并不完美,而且有很多 cmets,但这是因为我是 Kim,正在尝试新东西 提前感谢所有愿意提供帮助的人

import cv2
import pytesseract
import numpy as np
from PIL import ImageGrab
import pyautogui
def Contour(img):
    Contours,hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    for cnt in Contours:
        area = cv2.contourArea(cnt)
        # print(area)
        # if area<150: could be useded to be cpecific
        # we need a copy of the image so we dont draw on the original or thickness=-1
        cv2.drawContours(imgcpy, cnt, -1, (255,0,0), thickness=-1)

#pytesseract.pytesseract.tesseract_cmd= 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
cap= cv2
img = cv2.imread('D:\\opencv\\R\\img\\lec\\3.png')
imgcpy = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# for japanese txt = pytesseract.image_to_string(gray, lang='jpn')
txt = pytesseract.image_to_string(gray)

imgblur = cv2.GaussianBlur(img, (7, 7), 0)
imgcanny = cv2.Canny(img, 200, 200)
#imgDialation = cv2.dilate(imgcanny, kernel, iterations=1)
#imgeroded = cv2.erode(imgDialation, kernel, iterations=1)
imBlank = np.zeros_like(img)
# waste of time only the same picture work -_-
# imstack = np.hstack((gray,gray,gray))
Contour(imgcanny)
cv2.imshow('Contour', imgcpy)



#img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
print(txt)

print(Contour(imgcanny))
#cv2.imshow('test', img)
cv2.waitKey()

【问题讨论】:

    标签: python opencv opencv-drawcontour


    【解决方案1】:

    “第一个”问题解决了

    1. 得到一个面具,要么
      • 使用connectedComponents
      • 通过使用drawContours 将掩码填充到np.zeros((height, width), dtype=np.uint8)
    2. dilate面具,然后
    3. 从膨胀的版本中减去掩码(字面减法可以工作,但按位运算也可以)

    结果是一个蒙版,其中包含刚好在轮廓外部的像素。

    使用此掩码获取这些像素值:

    # have `mask` somehow, which should be dtype uint8
    
    dilated = cv.dilate(mask)
    surrounding = dilated - mask
    
    values = img[surrounding != 0] # numpy indexing using a boolean array
    meancolor = values.mean(axis=(0,1)) # sum/average over both axes
    

    “第二个”问题是您将单个轮廓传递给drawContours,它需要一个轮廓列表

    更改您的代码以传递 [cnt] 而不仅仅是 cnt

    cv2.drawContours(imgcpy, [cnt], -1, (255,0,0), thickness=-1)
    

    如果你只传递cnt,它会将points列表(轮廓是点列表)解释为contours列表,因此它将将每个点解释为一个轮廓......这只是一个点,而不是一个轮廓。

    【讨论】:

    • 抱歉重播晚了,非常感谢您的帮助,今天兼职结束后我会尝试解决方案
    • 我刚刚在我的答案中发现了一个错误。现在已更正。查找需要使用surrounding 掩码,而不是mask 掩码
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2013-04-23
    相关资源
    最近更新 更多