简体   繁体   English

Python + OpenCV:枚举矩阵

[英]Python + OpenCV: Enumerate Matrix

I am a newbie to Python. 我是Python的新手。

And I want to access Mat (a threshold binary image) element from opencv and create the a histogram according to the x-axis, and so I can do some image segmentation vertically. 我想从opencv访问Mat(一个阈值二进制图像)元素并根据x轴创建一个直方图,因此我可以垂直进行一些图像分割。

What I have done is to preprocess the image and enumerate twice as following. 我所做的是预处理图像并按以下方式枚举两次。

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)

And if I directly enumerate the threshold Mat like 如果我直接枚举Mat的阈值就好了

    for y, x in enumerate(thresh):

I can only enumerate from the outer y axis first then enumerate the x axis. 我只能先从外部y轴枚举,然后枚举x轴。 So how can I do this reversely? 那我该怎么做呢? My aim is to get the image like this: 我的目标是获得这样的图像:

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

Image references: 图片参考:

Jeff Yan, A Low-cost Attack on a Microsoft CAPTCHA Jeff Yan, 微软CAPTCHA的低成本攻击

If you want the number of black pixels for each x position, following your code this should work: 如果你想要每个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)

So basically you are looping over the x axis and, for each of its position, finding the amount of black pixels over the y axis, which is stored in the variable val . 所以基本上你是在x轴上循环,并且对于它的每个位置,找到y轴上的黑色像素量,它存储在变量val Finally you draw a line that has a height equal to val pixels at the x position you are looping that starts at the bottom of the image. 最后,您绘制一条高度等于val像素的线,在您从图像底部开始循环的x位置。

Hope this helped! 希望这有帮助!

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

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