如何使用python制作二进制图像? [英] How to make a binary image with python?

查看:216
本文介绍了如何使用python制作二进制图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 cv2.THRESH_BINARY 和函数

ret,im_thresh = cv2.threshold(gray_image,40,255, cv2.THRESH_BINARY)

ret, im_thresh = cv2.threshold( gray_image, 40, 255, cv2.THRESH_BINARY )

但是白色必须为1才能与我的程序配合使用.

BUT White must be 1 to Work with my program.

为了帮助我:

height = int(np.size(im_thresh, 0))
width = int(np.size(im_thresh, 1))

for x in range(height):
    for y in range(width):
        if im_thresh[x,y]==255:
            im_thresh[x,y] = 1

我的问题:有什么方法可以在python中更快地做到这一点?

推荐答案

尝试使用布尔索引来获取和设置数组的值,这样可以避免嵌套的for循环.

Try using a boolean index to get and set the values of the arrays, which avoids the nested for loop.

import numpy as np
from numpy import random

# Generating an image of values between 1 and 255. 
im_thresh = random.randint(1,256, (64,64))

# Set anything less than 255 to 0. Unnecessary if cv2 does this during threshold. 
# Must go before the operation below in order not to set all values to 0. 
im_thresh[im_thresh<255] = 0

# Set all values at indices where the array equals 255 to 1.
im_thresh[im_thresh==255] = 1

这篇关于如何使用python制作二进制图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆