TensorFLow能够识别的图像文件,可以通过numpy

本文介绍了使用TensorFlow处理图像数据的两种方法:一种是通过numpy和cv2等库直接操作图像,另一种是利用TensorFlow内置函数实现图像文件的读取与预处理。此外,还详细展示了如何构建图像数据读取的pipeline。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TensorFLow能够识别的图像文件,可以通过numpy,使用tf.Variable或者tf.placeholder加载进tensorflow;也可以通过自带函数(tf.read)读取,当图像文件过多时,一般使用pipeline通过队列的方法进行读取。下面我们介绍两种生成tensorflow的图像格式的方法,供给tensorflow的graph的输入与输出。

1

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import cv2  
  2. import numpy as np  
  3. import h5py  
  4.   
  5. height = 460  
  6. width = 345  
  7.   
  8. with h5py.File('make3d_dataset_f460.mat','r') as f:  
  9.     images = f['images'][:]  
  10.       
  11. image_num = len(images)  
  12.   
  13. data = np.zeros((image_num, height, width, 3), np.uint8)  
  14. data = images.transpose((0,3,2,1))  


先生成图像文件的路径:ls *.jpg> list.txt

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import cv2  
  2. import numpy as np  
  3.   
  4. image_path = './'  
  5. list_file  = 'list.txt'  
  6. height = 48  
  7. width = 48  
  8.   
  9. image_name_list = [] # read image  
  10. with open(image_path + list_file) as fid:  
  11.     image_name_list = [x.strip() for x in fid.readlines()]  
  12. image_num = len(image_name_list)  
  13.   
  14. data = np.zeros((image_num, height, width, 3), np.uint8)  
  15.   
  16. for idx in range(image_num):  
  17.     img = cv2.imread(image_name_list[idx])  
  18.     img = cv2.resize(img, (height, width))  
  19.     data[idx, :, :, :] = img  


2 Tensorflow自带函数读取

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. def get_image(image_path):  
  2.     """Reads the jpg image from image_path. 
  3.     Returns the image as a tf.float32 tensor 
  4.     Args: 
  5.         image_path: tf.string tensor 
  6.     Reuturn: 
  7.         the decoded jpeg image casted to float32 
  8.     """  
  9.     return tf.image.convert_image_dtype(  
  10.         tf.image.decode_jpeg(  
  11.             tf.read_file(image_path), channels=3),  
  12.         dtype=tf.uint8)  


 pipeline读取方法

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. # Example on how to use the tensorflow input pipelines. The explanation can be found here ischlag.github.io.  
  2. import tensorflow as tf  
  3. import random  
  4. from tensorflow.python.framework import ops  
  5. from tensorflow.python.framework import dtypes  
  6.   
  7. dataset_path      = "/path/to/your/dataset/mnist/"  
  8. test_labels_file  = "test-labels.csv"  
  9. train_labels_file = "train-labels.csv"  
  10.   
  11. test_set_size = 5  
  12.   
  13. IMAGE_HEIGHT  = 28  
  14. IMAGE_WIDTH   = 28  
  15. NUM_CHANNELS  = 3  
  16. BATCH_SIZE    = 5  
  17.   
  18. def encode_label(label):  
  19.   return int(label)  
  20.   
  21. def read_label_file(file):  
  22.   f = open(file, "r")  
  23.   filepaths = []  
  24.   labels = []  
  25.   for line in f:  
  26.     filepath, label = line.split(",")  
  27.     filepaths.append(filepath)  
  28.     labels.append(encode_label(label))  
  29.   return filepaths, labels  
  30.   
  31. # reading labels and file path  
  32. train_filepaths, train_labels = read_label_file(dataset_path + train_labels_file)  
  33. test_filepaths, test_labels = read_label_file(dataset_path + test_labels_file)  
  34.   
  35. # transform relative path into full path  
  36. train_filepaths = [ dataset_path + fp for fp in train_filepaths]  
  37. test_filepaths = [ dataset_path + fp for fp in test_filepaths]  
  38.   
  39. # for this example we will create or own test partition  
  40. all_filepaths = train_filepaths + test_filepaths  
  41. all_labels = train_labels + test_labels  
  42.   
  43. all_filepaths = all_filepaths[:20]  
  44. all_labels = all_labels[:20]  
  45.   
  46. # convert string into tensors  
  47. all_images = ops.convert_to_tensor(all_filepaths, dtype=dtypes.string)  
  48. all_labels = ops.convert_to_tensor(all_labels, dtype=dtypes.int32)  
  49.   
  50. # create a partition vector  
  51. partitions = [0] * len(all_filepaths)  
  52. partitions[:test_set_size] = [1] * test_set_size  
  53. random.shuffle(partitions)  
  54.   
  55. # partition our data into a test and train set according to our partition vector  
  56. train_images, test_images = tf.dynamic_partition(all_images, partitions, 2)  
  57. train_labels, test_labels = tf.dynamic_partition(all_labels, partitions, 2)  
  58.   
  59. # create input queues  
  60. train_input_queue = tf.train.slice_input_producer(  
  61.                                     [train_images, train_labels],  
  62.                                     shuffle=False)  
  63. test_input_queue = tf.train.slice_input_producer(  
  64.                                     [test_images, test_labels],  
  65.                                     shuffle=False)  
  66.   
  67. # process path and string tensor into an image and a label  
  68. file_content = tf.read_file(train_input_queue[0])  
  69. train_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)  
  70. train_label = train_input_queue[1]  
  71.   
  72. file_content = tf.read_file(test_input_queue[0])  
  73. test_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)  
  74. test_label = test_input_queue[1]  
  75.   
  76. # define tensor shape  
  77. train_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])  
  78. test_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])  
  79.   
  80.   
  81. # collect batches of images before processing  
  82. train_image_batch, train_label_batch = tf.train.batch(  
  83.                                     [train_image, train_label],  
  84.                                     batch_size=BATCH_SIZE  
  85.                                     #,num_threads=1  
  86.                                     )  
  87. test_image_batch, test_label_batch = tf.train.batch(  
  88.                                     [test_image, test_label],  
  89.                                     batch_size=BATCH_SIZE  
  90.                                     #,num_threads=1  
  91.                                     )  
  92.   
  93. print "input pipeline ready"  
  94.   
  95. with tf.Session() as sess:  
  96.     
  97.   # initialize the variables  
  98.   sess.run(tf.initialize_all_variables())  
  99.     
  100.   # initialize the queue threads to start to shovel data  
  101.   coord = tf.train.Coordinator()  
  102.   threads = tf.train.start_queue_runners(coord=coord)  
  103.   
  104.   print "from the train set:"  
  105.   for i in range(20):  
  106.     print sess.run(train_label_batch)  
  107.   
  108.   print "from the test set:"  
  109.   for i in range(10):  
  110.     print sess.run(test_label_batch)  
  111.   
  112.   # stop our queue threads and properly close the session  
  113.   coord.request_stop()  
  114.   coord.join(threads)  
  115.   sess.close()  



参考资料

TensorFlow中进行图像识别时,如果摄像头图像不显示出来,可能有以下几个原因: 1. **摄像头权限问题**:确保你的程序有权限访问摄像头。在不同的操作系统上,权限设置方式可能不同。例如,在Windows上,确保摄像头没有被其他程序占用;在Linux上,可以使用`ls /dev/video*`命令检查摄像头设备是否可用。 2. **代码问题**:检查代码中是否有错误,特别是与摄像头相关的部分。以下是一个简单的TensorFlow图像识别代码示例: ```python import cv2 import numpy as np import tensorflow as tf # 加载预训练的TensorFlow模型 model = tf.keras.models.load_model('path_to_your_model.h5') # 打开摄像头 cap = cv2.VideoCapture(0) while True: # 读取摄像头帧 ret, frame = cap.read() if not ret: break # 预处理图像 img = cv2.resize(frame, (224, 224)) img = np.expand_dims(img, axis=0) img = img / 255.0 # 进行预测 predictions = model.predict(img) # 显示结果 cv2.imshow('Image Recognition', frame) # 按下'q'键退出 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放摄像头并关闭窗口 cap.release() cv2.destroyAllWindows() ``` 3. **摄像头驱动问题**:确保摄像头驱动已正确安装。可以尝试更新摄像头驱动或使用其他摄像头测试。 4. **OpenCV问题**:确保OpenCV已正确安装,并且与Python版本兼容。可以尝试重新安装OpenCV: ```sh pip install opencv-python ``` 5. **其他问题**:如果以上方法都无法解决问题,可以尝试在不同的环境中运行代码,或者在不同的计算机上测试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值