代码整理个人DIY001

import chardet
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"#忽略警告默认1显示全部信息
os.environ["CUDA_VISIBLE_DEVICES"]="-1"#禁用GPU,默认1/0使用
tf.compat.v1.disable_eager_execution()
# # 建议使用GPU最小显存使用量
# config=tf.compat.v1.ConfigProto()
# config.gpu_options.allow_growth = True
# sess=tf.compat.v1.Session(config=config)
# with tf.io.gfile.GFile(filename,'rb') as f:
#     image_data = f.read()
# with tf.Session() as sess:
#     image_data = tf.image.decode_jpeg(image_data)
print("program starting......")
filename = 'D:\Pictures\cscscs\sc16.jpg'

img_content02 = tf.io.gfile.GFile(filename,'rb').read()
chardet.detect(img_content02)
print("数据类型",type(img_content02))
image_data=tf.image.decode_jpeg(img_content02,channels=3) #https://blog.csdn.net/qq_20084101/article/details/87440231
'''(
    contents,
    channels=0,1灰度-3RGB
    ratio=1,快速缩小倍数1,2,4,8
    fancy_upscaling=True,
    try_recover_truncated=False,
    acceptable_fraction=1,
    dct_method='',
    name=None)'''

# image_data2 = tf.image.convert_image_dtype(image_data, dtype=tf.float32)

# print(chardet.detect_all(image_data2))

sess=tf.compat.v1.Session()
image = sess.run(image_data)
# image = sess.run(image_data2)
h,w,c=image.shape

img_data = sess.run(tf.image.rgb_to_grayscale(image_data))  # 灰度化
print('大小:{}'.format(img_data.shape))
print("类型:%s" % type(img_data))
# print(img_data)
print("origin picture:",image.shape)
print("类型:%s" % type(image))
print("数据类型",type(img_data))
plt.imshow(img_data, 'hsv')
img_out2t='D:\Pictures\cscscs\sc5256.jpg'

img_resized = tf.image.resize(img_data, size=[300, 300],method=tf.image.ResizeMethod.AREA)

print("resized picture:",img_resized.shape)
# img_output='D:\Pictures\cscscs\sc333.jpg'
# # coding:unicode
img_wt=tf.image.encode_jpeg(img_resized)
#
# # tf.image.convert_image_dtype(img_resized,"unicode")
# # # tf.image.convert_image_dtype(img_resized,"utf-8")
# # # tf.image.convert_image_dtype(img_resized,"float32")
# # img_wt=tf.image.encode_jpeg(img_resized,format=None)
resized_wt = tf.image.convert_image_dtype(img_resized)
# # resized_wt = tf.image.convert_image_dtype(img_resized, dtype=tf.uint8)
# # resized_wt  = np.array(resized_wt, dtype='float32')
# # print("leixxx",type(resized_wt))
# # img_write= tf.io.gfile.GFile(img_output,'wb').write(resized_wt)
# # resized = tf.image.convert_image_dtype(img_resized, dtype=tf.uint8)
encoded_image = tf.image.encode_jpeg(resized_wt,dtype=tf.uint8)
img = tf.image.encode_jpeg(encoded_image)
# tf.io.write_file(img_resized,'D:\Pictures\cscscs\sc35555.jpg')
with tf.io.gfile.GFile('sc355.jpg', 'wb') as file:
    file.write(img)

print("well done!!!")























# NBNBNB精简版
'''NBNBNB精简版

# -*- coding: utf-8 -*-
import tensorflow as tf
import matplotlib.pyplot as plt
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"#忽略警告默认1显示全部信息
os.environ["CUDA_VISIBLE_DEVICES"]="-1"#禁用GPU,默认1/0使用
tf.compat.v1.disable_eager_execution()
# # 建议使用GPU最小显存使用量
# config=tf.compat.v1.ConfigProto()
# config.gpu_options.allow_growth = True
# sess=tf.compat.v1.Session(config=config)

filename = 'D:\Pictures\cscscs\sc15.jpg'
# with tf.io.gfile.GFile(filename,'rb') as f:
#     image_data = f.read()
# with tf.Session() as sess:
#     image_data = tf.image.decode_jpeg(image_data)
img_content02 = tf.io.gfile.GFile(filename,'rb').read()
image_data=tf.io.decode_image(img_content02)
sess=tf.compat.v1.Session()
image = sess.run(image_data)
h,w,c=image.shape
plt.imshow(image[:,:,:])
print(image.shape)
print(image[:,:,2])

'''
'''
# -*- coding: utf-8 -*-
import tensorflow as tf
import matplotlib.pyplot as plt
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
tf.compat.v1.disable_eager_execution()
# # 建议使用GPU最小显存使用量
# config=tf.compat.v1.ConfigProto()
# config.gpu_options.allow_growth = True
# sess=tf.compat.v1.Session(config=config)

filename = 'D:\Pictures\cscscs\sc15.jpg'

# with tf.io.gfile.GFile(filename,'rb') as f:
#     image_data = f.read()
#
# with tf.Session() as sess:
#     image_data = tf.image.decode_jpeg(image_data)
img_content02 = tf.io.gfile.GFile(filename,'rb').read()

image_data=tf.io.decode_image(img_content02)

sess=tf.compat.v1.Session()
# sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(
#     allow_soft_placement=True,
#     log_device_placement=True))
image = sess.run(image_data)
h,w,c=image.shape
# assert c==1
# image = image.reshape(h,w)
# plt.imshow(image)
c=0
plt.imshow(image[:,:,:])
print(image.shape)
print(image[:,:,2])

'''

# 数据集建立NBNBbddd
'''
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
import os
import pathlib
import random
import matplotlib.pyplot as plt

data_root = pathlib.Path('D:\Pictures\\NBNB01\Dataset')

##########################################

# #原始图片地址
# # orig_picture = r'D:\PyCharm\KinZhang_First_ImageDetection\data'
# orig_picture = r'D:\\Pictures\\NBNB01\\Dataset\\sds'
#
# #生成图片地址
# # gen_picture = r'D:\PyCharm\KinZhang_First_ImageDetection\generate_data'
# gen_picture = r'D:\\Pictures\\NBNB01\\Dataset\\generate_date'

##########################################


print(data_root)
for item in data_root.iterdir():
    print(item)

all_image_paths = list(data_root.glob('*/*'))
all_image_paths = [str(path) for path in all_image_paths]
random.shuffle(all_image_paths)
image_count = len(all_image_paths)
print(image_count) ##统计共有多少图片
for i in range(10):
 print(all_image_paths[i])
 label_names = sorted(item.name for item in data_root.glob('*/') if item.is_dir())
 print(label_names)  # 其实就是文件夹的名字
 label_to_index = dict((name, index) for index, name in enumerate(label_names))
 print(label_to_index)
 all_image_labels = [label_to_index[pathlib.Path(path).parent.name]
                     for path in all_image_paths]

 print("First 10 labels indices: ", all_image_labels[:10])

 # 预处理
 def preprocess_image(image):
     image = tf.image.decode_jpeg(image, channels=3)
     image = tf.image.resize(image, [100, 100])
     image /= 255.0  # normalize to [0,1] range
     # image = tf.reshape(image,[100*100*3])
     return image

 def load_and_preprocess_image(path, label):
     image = tf.io.read_file(path)
     return preprocess_image(image), label

#  构建一个 tf.data.Dataset
ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels))
train_data = ds.map(load_and_preprocess_image).batch(16)

tf.saved_model.save(train_data, "savedmSBSB")
print("well done!!!")
# 不对劲sbsbsb,,,路径合适成功一半HHGGG--数据集建立,也不知道对不对
'''

# '''nbnbNBNBtftftf测试改大小五种方法'''
'''
# -*- coding: utf-8 -*-

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"#忽略警告默认1显示全部信息
os.environ["CUDA_VISIBLE_DEVICES"]="-1"#禁用GPU,默认1/0使用
tf.compat.v1.disable_eager_execution()
# # 建议使用GPU最小显存使用量
# config=tf.compat.v1.ConfigProto()
# config.gpu_options.allow_growth = True
# sess=tf.compat.v1.Session(config=config)
# with tf.io.gfile.GFile(filename,'rb') as f:
#     image_data = f.read()
# with tf.Session() as sess:
#     image_data = tf.image.decode_jpeg(image_data)
print("program starting......")
filename = 'D:\Pictures\cscscs\sc15.jpg'

img_content02 = tf.io.gfile.GFile(filename,'rb').read()
image_data=tf.image.decode_jpeg(img_content02,channels=3) #https://blog.csdn.net/qq_20084101/article/details/87440231
sess=tf.compat.v1.Session()
image = sess.run(image_data)
h,w,c=image.shape

img_data = sess.run(tf.image.rgb_to_grayscale(image_data))  # 灰度化
print('大小:{}'.format(img_data.shape))
print("类型:%s" % type(img_data))
# print(img_data)
print("origin picture:",image.shape)
print("类型:%s" % type(image))

img_resized = tf.image.resize(img_data, size=[300, 300],method=tf.image.ResizeMethod.AREA,
                              preserve_aspect_ratio=False,antialias = False,name = None)
# img_resized = tf.image.resize(img_data, size=[300, 300],method=tf.image.ResizeMethod.BILINEAR,
#                               preserve_aspect_ratio=False,antialias = False,name = None)
# img_resized = tf.image.resize(img_data, size=[300, 300])
# img_resized = tf.image.resize(img_data, size=[300, 300],method=tf.image.ResizeMethod.MITCHELLCUBIC,
#                               preserve_aspect_ratio=False,antialias = False,name = None)
# img_resized = tf.image.resize(img_data, size=[300, 300],method=tf.image.ResizeMethod.BICUBIC,
#                               preserve_aspect_ratio=False,antialias = False,name = None)
# img_resized = tf.image.resize(img_data, size=[300, 300],method=tf.image.ResizeMethod.GAUSSIAN,
#                               preserve_aspect_ratio=False,antialias = False,name = None)
# img_resized = tf.image.resize(img_data, size=[300, 300],method=tf.image.ResizeMethod.LANCZOS3,
#                               preserve_aspect_ratio=False,antialias = False,name = None)
# img_resized = tf.image.resize(img_data, size=[300, 300],method=tf.image.ResizeMethod.NEAREST_NEIGHBOR,
#                               preserve_aspect_ratio=False,antialias = False,name = None)
# 四种方法,默认双线性,0123,,0:双线性差值。1:最近邻居法。2:双三次插值法。3:面积插值法。最后默认,其他难搞
# 对所有计算机视觉工作者的简短警告:请勿使用任何tf.image.resize函数!默认是什么方式
print("resized picture:",img_resized.shape)
print("well done!!!")
'''

第二个,好不好使用的测试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海宝7号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值