输入图像为Contours_X.png
[Contors_X.png:PNG图像数据,819 x 1154,8位灰度,非隔行扫描]:
从Python Find Contours white region only OpenCV个代码中窃取代码:
import cv2 as cv
import numpy as np
def generate_X_Y(image_path):
image = cv.imread(image_path)
# image = cv.imread(image_path, cv.IMREAD_UNCHANGED)
cv.imwrite("image_ori.png" , image)
print('image[0] : ', image[0])
gray = cv.cvtColor(image, cv.COLOR_RGBA2GRAY)
print('gray[0] : ', gray[0])
## CHANGED TO:
ret, thresh = cv.threshold(gray, 128, 255, cv.THRESH_BINARY_INV)
cv.imwrite("image2.png", thresh)
contours, hierarchies = cv.findContours(thresh, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
blank = np.zeros(thresh.shape[:2], dtype='uint8')
cv.drawContours(blank, contours, -1, (255, 0, 0), 1)
cv.imwrite("Contours.png", blank)
print('len(contours) : ' , len(contours))
for i in contours:
cv.drawContours(image, [i], -1, (0, 255, 0), 2)
cv.imwrite("image.png", image)
if __name__ == '__main__':
image_path = 'Contours_X.png' # Provide the correct path in Colab
# image_path = 'input_alpha.png'
generate_X_Y(image_path)
我得到输出image.png
[Image.png:PNG图像数据,819 x 1154,8位/彩色RGB,非隔行扫描
]:
使用input_alpha_2.png
[Input_Alpha_2.png:PNG图像数据,input_alpha_2.png
0 x 1200,8位/彩色RGBA,非隔行扫描]:
和代码:
import cv2 as cv
import numpy as np
def generate_X_Y(image_path):
# image = cv.imread(image_path)
image = cv.imread(image_path, cv.IMREAD_UNCHANGED)
cv.imwrite("image_ori.png" , image)
print('image[0] : ', image[0])
gray = cv.cvtColor(image, cv.COLOR_RGBA2GRAY)
print('gray[0] : ', gray[0])
## CHANGED TO:
ret, thresh = cv.threshold(gray, 128, 255, cv.THRESH_BINARY_INV)
cv.imwrite("image2.png", thresh)
contours, hierarchies = cv.findContours(thresh, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
blank = np.zeros(thresh.shape[:2], dtype='uint8')
cv.drawContours(blank, contours, -1, (255, 0, 0), 1)
cv.imwrite("Contours.png", blank)
print('len(contours) : ' , len(contours))
for i in contours:
cv.drawContours(image, [i], -1, (0, 255, 0), 20)
cv.imwrite("image.png", image)
if __name__ == '__main__':
# image_path = 'Contours_X.png' # Provide the correct path in Colab
image_path = 'input_alpha_2.png'
generate_X_Y(image_path)
我得到image.png
[Image.png:PNG图像数据,image.png
0 x 1200,8位/彩色RGBA,非隔行扫描]:
为什么我不像第一个例子那样在主题周围画一个漂亮的绿色边框?
正如 comments 中所建议的:
您的基本BGR图像(在Alpha通道下)具有您的绿色线条.Alpha通道正在覆盖它).移除Alpha通道以查看它.
并做到这一点:
cv.imwrite("image.png", image[:,:,:3])
我得到image.png: PNG image data, 1000 x 1200, 8-bit/color RGBA, non-interlaced分:
但我仍然不明白透明的Alpha通道如何隐藏轮廓,为什么我会得到灰色背景,我相信这可能是我图像中最大轮廓的区域,即方形外部黑色边框?
有关这方面的更多信息,请使用:
cntsSorted = sorted(contours, key = lambda x: cv.contourArea(x) , reverse=True)
for index , i in enumerate(cntsSorted) :
print(cv.contourArea(i))
if index > 0 :
cv.drawContours(image, [i], -1, (0, 255, 0), 20)
cv.imwrite("image.png", image)
cv.imwrite("image_rem.png", image[:,:,:3])
第二幅图像没有更多的外部绿色边框,但仍然保持深灰色背景.