【问题标题】:Read pixels from image in python as in Labview像在 Labview 中一样从 python 中的图像中读取像素
【发布时间】:2021-01-22 14:00:03
【问题描述】:

我必须在 Labview 中集成我的 python 代码,并且我正在比较两者中图像的像素值。 Labview 给出了 U16 中的像素值,因此我想在 python 中查看enter image description heresame 图像的像素值,看看这些值是否相同。 有人可以帮我提供相同的代码吗? 我的图像是黑白的 png 图像。

【问题讨论】:

    标签: python image


    【解决方案1】:

    您可以为此使用 PILOpenCVwandscikit-image。这是一个PIL版本:

    from PIL import Image
    import numpy as np
    
    # Open image
    im = Image.open('dXGat.png')
    
    # Make into Numpy array for ease of access
    na = np.array(im)
    
    # Print shape (pixel dimensions) and data type
    print(na.shape,na.dtype)    # prints (256, 320) int32
    
    # Print brightest and darkest pixel
    print(na.max(), na.min())
    
    # Print top-left pixel
    print(na[0,0])              # prints 25817
    
    # WATCH OUT FOR INDEXING - IT IS ROW FIRST
    # print first pixel in second row
    print(na[1,0])              # prints 24151
    
    # print first 4 columns of first 2 rows
    print(na[0:2,0:4])
    

    输出

    array([[25817, 32223, 30301, 33504],
           [24151, 22934, 19859, 21460]], dtype=int32)
    

    如果您更喜欢使用 OpenCV,请更改以下几行:

    from PIL import Image
    import numpy as np
    
    # Open image
    im = Image.open('dXGat.png')
    
    # Make into Numpy array for ease of access
    na = np.array(im)
    

    到这里:

    import cv2
    import numpy as np
    
    # Open image
    na = cv2.imread('dXGat.png',cv2.IMREAD_UNCHANGED)
    

    如果您只想一次性检查像素,您可以在终端中使用 ImageMagick

    magick dXGat.png txt: | more
    

    样本输出

    # ImageMagick pixel enumeration: 320,256,65535,gray
    0,0: (25817)  #64D964D964D9  gray(39.3942%)
    1,0: (32223)  #7DDF7DDF7DDF  gray(49.1691%)
    2,0: (30301)  #765D765D765D  gray(46.2364%)
    3,0: (33504)  #82E082E082E0  gray(51.1238%)
    ...
    ...
    317,255: (20371)  #4F934F934F93  gray(31.0842%)
    318,255: (20307)  #4F534F534F53  gray(30.9865%)
    319,255: (20307)  #4F534F534F53  gray(30.9865%)
    

    【讨论】:

    • 您好,感谢您的帮助。如何获取 U16 中的值。
    • 如果 U16 表示无符号 16 位,只需像这样更改类型 na = np.array(im).astype(np.uint16)
    • 嗨,它仍然与我们从 Labview 得到的答案不匹配
    • 相对于 PILOpenCVImageMagick 的想法,您的值似乎放大了 64 倍,所以你可以使用na = (np.array(im)//64).astype(np.uint16)
    • 我需要更多帮助。在我的项目中计算后,我想打印包括所有数字的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多