填充区域以黑线标记

时间:2017-04-23 08:12:45

标签: python opencv image-processing simplecv

我正在尝试查找图像中黑线所包含的区域。

以下是样本起始图像" photo.jpg":

Sample starting image "photo.jpg"

我已经使用了OpenCV和SimpleCV。

以下是代码:

from SimpleCV import Camera, Display, Image, Color
import time
import cv2
import numpy as np

n_image = Image('photo.jpg')
n_image2 = n_image.crop(55, 72, 546, 276)  #Crop X,Y,W,H
n_image2.save('photo_2.jpg')
imagea = Image("photo_2.jpg")

greya = imagea.stretch(50).invert()  #50=Blackness level of Black
greya.show()
greya.save('photo_2-GREY.jpg')

im = cv2.imread('photo_2-GREY.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(imgray,220,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
largest_areas = sorted(contours, key=cv2.contourArea)
cv2.drawContours(im, [largest_areas[-2]], 0, (255,255,255,255), -1)

cv2.drawContours(im,contours,-1,(255,255,255),-1)
cv2.imshow('Image Window',im)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('photo_3.jpg',im)

n_image = Image('photo_3.jpg')
mask = n_image.colorDistance((127, 127, 127))

mask.show()
mask.save('mask.jpg')
time.sleep(3)

binarised = mask.binarize()
blobs = binarised.findBlobs()
blobs.show(width=3)
time.sleep(60)

individualareaofholes = blobs.area()
compositeareaofholes = sum(individualareaofholes)
orig_area = 132432
finalarea = (orig_area - compositeareaofholes)
res = round(((finalarea/orig_area)*100),0)

print "Area is %d" % res

这是图像" mask.jpg"用于区域计算:

Generated image "mask.jpg"

观察:  1.白色区域内的黑色斑块" mask.jpg"  2.左下角的白色部分带有" TAXI"

如何消除它们? 我只是希望黑色线条内的所有内容都被吞噬,并且在计算区域时不考虑线条外的所有内容。

1 个答案:

答案 0 :(得分:0)

我认为你的解决方案很复杂(我可能错了)。我试图修改你的代码并获得黑色边界内的区域。不确定该区域是否正确但它将为您提供一种微调方法。

import cv2
import numpy as np

n_image = cv2.imread('5GZ6X.jpg') # Your original image

imgray =  cv2.cvtColor(n_image,cv2.COLOR_BGR2GRAY)
im_new = np.zeros_like(imgray)
ret,thresh = cv2.threshold(imgray,10,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
largest_areas = sorted(contours, key=cv2.contourArea)
cv2.drawContours(im_new, [largest_areas[-2]], 0, (255,255,255,255), -1)

image_masked = cv2.bitwise_and(imgray, imgray, mask=im_new)

area = cv2.contourArea(largest_areas[-2])

for contour in largest_areas:
    areas = cv2.contourArea(contour)
    if areas > 300:
        print areas

print 'Complete area :' + str(n_image.shape[0] * n_image.shape[1])

print 'Area of selected region : ' + str(area)

cv2.imshow('main', image_masked)
cv2.waitKey(1000)

我从中得到的结果是

113455.5
135587.0
303849.0
Complete area :307200
Area of selected region : 135587.0

在使用生成的轮廓(最大轮廓)掩蔽图像后,我得到了这个图像结果

enter image description here

希望这有帮助!祝你好运:)