python合集(显示图像,黑白化、二值化,处理excel、画有向图无向图赋权图网络图NetworkX库)

EXCEL数据读取代码

https://blog.csdn.net/weixin_43820813/article/details/124467183

网络图、有向图无向图(只适合少量的数据)

https://blog.csdn.net/tan45du_yuan/article/details/109464240
https://blog.csdn.net/qq_55851911/article/details/124774716

图像批量变为黑白

批量处理图片,把彩色的图片变为黑白。
这里只需要更改Path的地址就可以了。
图片是直接在图片上修改的,所以修改前可以先对原图片进行备份呢

代码如下:

import cv2
import os
def re_name (path) :
    files = os.listdir (path)
    for i, file in enumerate (files) :
        try:
            new_file_name = os.path.join (path, str(i) + ' . jpg')
            old_file_name = os.path. join (path, file)
            os. rename (old_file_name,new_file_name)
        except:
            continue
def gray_pic(path) :
    files =os.listdir(path)
    for file in enumerate (files) :
        try:
            pic = path +"/"+str(file[1])
            original_img = cv2. imread (pic)
            gray = cv2. cvtColor (original_img, cv2 . COLOR_BGR2GRAY)
            cv2. imwrite (path + "/" + str (file[1]),gray)
        except:
            continue
path = "F:/DATA/archive (kaggle)/Segmented/Pro"
#re_ name (path)
gray_pic (path)

导入与显示图像

载入图像后要显示图像 要用这两个函数才有用
在这里插入图片描述其实 图像存在计算机里面,是一个一个的像素点。
就比如我的这张图,就是一个二维数组,数组里面存的就是像素值

批量二值化

下面是我批量处理图片——二值化 黑白转换的代码 :

可以试着参考这一篇:彩色图像二值化处理

以及这篇:python图像的二值化

我的代码:

import cv2
import matplotlib.image as img
import matplotlib.pyplot as plt
import numpy as np
import scipy.misc
import os
file_dir = "F:/DATA/PM_400/tain/masks" # 图像文件路径
def imgBinaryThreshold(img, threshold=128):
    rows = img.shape[0]
    cols = img.shape[1]
    for i in range(rows):
        for j in range(cols):
            gray = img[i, j]
            if (gray.all() ==0):
                img[i, j] = 255
            else :
                img[i, j] = 0
    return img.astype(np.uint8)
def read_directory(directory_name):
    for filename in os.listdir(directory_name):
        if filename[-4:] in ['.JPG']:  # 判断文件是否为图片格式
            print(filename)  # 仅仅是为了测试
            img = cv2.imread(directory_name + "/" + filename)
            img = imgBinaryThreshold(img)
            #####保存图片#########
            cv2.imwrite("F:/DATA/Masks" + "/" + filename, img)
        else:
            continue
        cv2.imwrite("F:/DATA/PM_400/tain/test" + "/" + filename, img)
if __name__ == "__main__":
    read_directory(file_dir)

只是这个代码一个像素点一个像素点的遍历真的! 好慢啊

猜你喜欢

转载自blog.csdn.net/qq_52626583/article/details/126713695
今日推荐