用黑色lin标记的填充区域

2024-09-30 10:35:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到包含在图像中黑线内的区域。在

这是示例起始图像“照片.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

这是图像“面具.jpg“用于面积计算:

Generated image "mask.jpg"

注意: 1白色区域内的黑色斑块面具.jpg" 2左下角有“出租车”字样的白色部分

我如何消除它们? 我只想在计算面积时,把黑线内的所有东西都吞掉,线外的一切都不要计算在内。在


Tags: 图像imageimporttimesaveshowmaskarea
1条回答
网友
1楼 · 发布于 2024-09-30 10:35:57

我认为你在使你的解决方案复杂化(我可能错了)。我试着修改你的代码,得到黑边界内的区域。不确定该区域是否正确,但它将为您提供微调的方法。在

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)

我得到的结果是

^{pr2}$

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

enter image description here

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

相关问题 更多 >

    热门问题