python常用代码整理

1. 黑白图、三通道图转化为单通道图

第一种办法(读取时就转化):img = cv2.imread('test.jpg', 0) # 参数0等价于:cv2.IMREAD_GRAYSCALE。 如果不加0,会默认读取为三通道图像,即便原图像是灰度图。
第二种办法(读取后再转化):img = cv2.cvtColor(img , cv2.COLOR_RGB2GRAY)

PIL的办法(读取时就转化): img = Image.open('test.jpg').convert('L') # 参数为"1"时示意转化为二值化图(位深度为1,每个像素点的值为0或1)

2.读写txt

    data_path = '../../data'
    f_Edges = data_path + '/{}{}'.format('lines', '_Edge.txt')
    with open(f_Edges, 'w') as file:
        for a, l, lc in zip(axes, lines, line_colors):
            for i in range(len(l)):
                #写入一条记录
                file.writelines('{} {} {} {}\n'.format(l[i, 0, 0], l[i, 1, 0], l[i, 0, 1], l[i, 1, 1]))

 3.np数组维度变换

import cv2
import numpy as np
image_path='v1.1/train/Z_3_19_DOM.jpg'
#image1 = cv2.imread(image_path,0)
image1 = cv2.imread(image_path)

print('读取原始RGB图像维度:{}'.format(image1.shape))

image1 = image1.astype(np.float32) / 255.

img = image1.transpose(2,0,1)
print('图像维度调整:{}'.format(img.shape))
#print(image1)

h, w = image1.shape[:2]
print('图像尺寸:{},{}'.format(h, w))

#-----------------------------------------------------
arrays = np.empty((0,1, h, w)) #创建空数组
tmp=img[0,:,:]
tmp1=img[1,:,:]
tmp2=img[2,:,:]
print('图像单通道升高维度2次:{}'.format(tmp[None][None].shape))
arrays = np.concatenate((arrays, tmp[None][None]), axis=0)
arrays = np.concatenate((arrays, tmp1[None][None]), axis=0)
arrays = np.concatenate((arrays, tmp2[None][None]), axis=0)

image_gray = cv2.imread(image_path,0)
img_g = image_gray[None][None]
#c_gray=img_g.transpose(0,1,2)
arrays = np.concatenate((arrays, img_g), axis=0)

print('动态数组:{}'.format(np.shape(arrays)))
print(type(arrays))

 4.数组元素访问:

import numpy as zw # 导入NumPy模块,并简写为zw
biaoxing=zw.array([23,43,65,76,83,34,1,34,56,97,32,32,36,61,42])# 创建数组biaoxing
print(biaoxing[1:6])# []中的数值为要选取索引值1(第2个元素)到索引值6(第7个元素)之间的元素
print(biaoxing[4:-3])# []中的数值为要选取索引值4(第5个元素)到索引值-3(倒数第3个元素)之间的元素
print(biaoxing[:6])# []中的数值为忽略起始元素,只指明了结束位置。
print(biaoxing[4:])# []中的数值为忽略了区间的结束位置,只指明了起始位置。

 缩放图像

import cv2
import numpy as np

def resize_and_crop(image, size, interp_mode=None):
    """ Apply a central crop to an image to resize it to a fixed size. """
    source_size = np.array(image.shape[:2], dtype=float)  # 读取宽高
    target_size = np.array(size, dtype=float)

    # Scale缩放比例
    scale = np.amax(target_size / source_size)
    inter_size = np.round(source_size * scale).astype(int)  # 比例取整
    if interp_mode is None:
        interp_mode = cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR
    image = cv2.resize(image, (inter_size[1], inter_size[0]),interpolation=interp_mode)
    # Central crop
    pad = np.round((source_size * scale - target_size) / 2.).astype(int)
    image = image[pad[0]:(pad[0] + int(target_size[0])),pad[1]:(pad[1] + int(target_size[1]))]

    return image

image_path='v1.1/train/Z_3_19_DOM.jpg'
image1 = cv2.imread(image_path)
print('读取原始RGB图像维度:{}'.format(image1.shape))
rgb_img = resize_and_crop(image1,[512,512])
print('缩放后RGB图像维度:{}'.format(rgb_img.shape))
cv2.imwrite('resize.png',rgb_img)

 5.

# [m : ] 代表列表中的第m+1项到最后一项
# [ : n] 代表列表中的第一项到第n项
# [-1] 代表去到最后一项
# [:-1]代表除了最后一个都获取到
# [::-1]代表逆序取,从后向前取
# [2::-1]代表从下标从0到2的三个数,逆序取
# [1:]代表从下标为1开始取到最后一个数
# https://www.runoob.com/numpy/numpy-ndarray-object.html
# https://blog.csdn.net/qq_51478745/article/details/127401026

import numpy as np

a = np.arange(10)  # [0 1 2 3 4 5 6 7 8 9]

print("原始数组:{}".format(a))

print("从第3个元素到最后一个:")
print(a[3:])
print("从第1个元素到5个:")
print(a[:5])
print("最后x项:")
print(a[-1])
print(a[-2])
print("代表除了最后一个都获取到")
print(a[:-1])
print("代表逆序取,从后向前取")
print(a[::-1])
print("代表从下标从0到2的三个数,逆序取")
print(a[2::-1])

 

posted @ 2024-03-25 18:19  太一吾鱼水  阅读(38)  评论(0编辑  收藏  举报