繁体   English   中英

Python + OpenCV:枚举矩阵

[英]Python + OpenCV: Enumerate Matrix

我是Python的新手。

我想从opencv访问Mat(一个阈值二进制图像)元素并根据x轴创建一个直方图,因此我可以垂直进行一些图像分割。

我所做的是预处理图像并按以下方式枚举两次。

def crack(src):
    #src is a binary image 

    src = cv2.resize(src, (0,0), fx=6, fy=6)
    thresh = preprocessing(src)

    #create empty histogram
    print(thresh.shape)
    height, width = thresh.shape
    size = height ,255,  3
    hist = np.zeros(size, dtype=np.uint8)

    #enumerate elements
    for y, x in enumerate(thresh):
        val = 0
        for x, pix in enumerate(x):
            val = val+ pix/255
            print y,x, val
        cv2.rectangle(hist, (y, 255-val), (y+val, 255-val+1), (0, 255, 0), 1)

    cv2.imshow("thresh", thresh)
    cv2.imshow("hist", hist)

如果我直接枚举Mat的阈值就好了

    for y, x in enumerate(thresh):

我只能先从外部y轴枚举,然后枚举x轴。 那我该怎么做呢? 我的目标是获得这样的图像:

image1 http://7xsnr6.com2.z0.glb.clouddn.com/QQ%E5%9B%BE%E7%89%8720160509184009.jpg

图片参考:

Jeff Yan, 微软CAPTCHA的低成本攻击

如果你想要每个x位置的黑色像素数,遵循你的代码,这应该工作:

# Enumerate elements
for x in range(width):
    val = 0
    for y in range(height):
        val += (255-thresh[y, x])/255
        print y, x, val
    cv2.line(thresh, (x, height-val-1), (x, height-1), (0, 255, 0), 1)

所以基本上你是在x轴上循环,并且对于它的每个位置,找到y轴上的黑色像素量,它存储在变量val 最后,您绘制一条高度等于val像素的线,在您从图像底部开始循环的x位置。

希望这有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM