У меня есть несколько кадров TIFF, и я попытался вычислить значения температуры, чтобы определить частоту дыхания.
Я не понимаю, правильно ли код извлек значения температуры. Вместо этого он, похоже, генерировал случайные значения или автоматически преобразовывал кадры в RGB или 8-битные оттенки серого.
Источник данных можно найти по следующей ссылке: источник данных
Ожидаемый результат должен выглядеть следующим образом: ссылка
После запуска кода выходной сигнал выглядит так, как показано здесь: вывод
import tifffile as tiff
import cv2
import numpy as np
import os
import argparse
import csv
import pandas as pd
import matplotlib.pyplot as plt
# Construct argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", required=True, help="Path to input directory containing TIFF files")
args = vars(ap.parse_args())
input_dir = args["video"]
print("Input directory: " + input_dir)
def select_roi(image):
"""
Allows user to select a region of interest (ROI) from the 16-bit image.
"""
# Normalize 16-bit data for display without altering its original values
normalized_image = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
color_map = cv2.applyColorMap(normalized_image, cv2.COLORMAP_JET)
cv2.imshow("Select Nose", color_map)
bbox = cv2.selectROI("Select Nose", color_map, fromCenter=False, showCrosshair=True)
cv2.destroyAllWindows()
# Print ROI coordinates
x, y, w, h = bbox
print(f"ROI's boundary is x1={x}, y1={y}, x2={x+w}, y2={y+h}")
return bbox
# Open CSV file for writing results
csv_file = "nose_pixel_values.csv"
with open(csv_file, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Frame", "Average Pixel Value"]) # CSV header
# Initialize ROI coordinates
x, y, w, h = None, None, None, None
# Loop through all TIFF files in the specified directory
for tiff_file in sorted(os.listdir(input_dir)):
if tiff_file.endswith(".tiff"):
file_path = os.path.join(input_dir, tiff_file)
with tiff.TiffFile(file_path) as tif:
gray16_frames = tif.asarray()
print(f"Processing '{tiff_file}' with {len(gray16_frames)} frames.")
# Get ROI from the first frame of the first TIFF file only
if x is None:
first_frame = gray16_frames[0]
bbox = select_roi(first_frame)
x, y, w, h = bbox
for i, frame in enumerate(gray16_frames):
# Extract the ROI based on the selected bbox
roi = frame[y:y+h, x:x+w]
# Calculate the average pixel value in the ROI (16-bit)
avg_pixel_value = np.mean(roi)
print(f"Frame {i}: Average pixel value : {avg_pixel_value}")
print(f"Frame {i}: shape : {frame.shape}, data type : {frame.dtype}, min: {frame.min()}, max: {frame.max()}")
# Write the result to the CSV file
with open(csv_file, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([i, avg_pixel_value])
print(f"Finished processing all files.")
Подробнее здесь: https://stackoverflow.com/questions/792 ... o-rgb-here
Здесь термокадры конвертируются в RGB? ⇐ Python
Программы на Python
1732978270
Anonymous
У меня есть несколько кадров TIFF, и я попытался вычислить значения температуры, чтобы определить частоту дыхания.
Я не понимаю, правильно ли код извлек значения температуры. Вместо этого он, похоже, генерировал случайные значения или автоматически преобразовывал кадры в RGB или 8-битные оттенки серого.
Источник данных можно найти по следующей ссылке: источник данных
Ожидаемый результат должен выглядеть следующим образом: ссылка
После запуска кода выходной сигнал выглядит так, как показано здесь: вывод
import tifffile as tiff
import cv2
import numpy as np
import os
import argparse
import csv
import pandas as pd
import matplotlib.pyplot as plt
# Construct argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", required=True, help="Path to input directory containing TIFF files")
args = vars(ap.parse_args())
input_dir = args["video"]
print("Input directory: " + input_dir)
def select_roi(image):
"""
Allows user to select a region of interest (ROI) from the 16-bit image.
"""
# Normalize 16-bit data for display without altering its original values
normalized_image = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
color_map = cv2.applyColorMap(normalized_image, cv2.COLORMAP_JET)
cv2.imshow("Select Nose", color_map)
bbox = cv2.selectROI("Select Nose", color_map, fromCenter=False, showCrosshair=True)
cv2.destroyAllWindows()
# Print ROI coordinates
x, y, w, h = bbox
print(f"ROI's boundary is x1={x}, y1={y}, x2={x+w}, y2={y+h}")
return bbox
# Open CSV file for writing results
csv_file = "nose_pixel_values.csv"
with open(csv_file, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Frame", "Average Pixel Value"]) # CSV header
# Initialize ROI coordinates
x, y, w, h = None, None, None, None
# Loop through all TIFF files in the specified directory
for tiff_file in sorted(os.listdir(input_dir)):
if tiff_file.endswith(".tiff"):
file_path = os.path.join(input_dir, tiff_file)
with tiff.TiffFile(file_path) as tif:
gray16_frames = tif.asarray()
print(f"Processing '{tiff_file}' with {len(gray16_frames)} frames.")
# Get ROI from the first frame of the first TIFF file only
if x is None:
first_frame = gray16_frames[0]
bbox = select_roi(first_frame)
x, y, w, h = bbox
for i, frame in enumerate(gray16_frames):
# Extract the ROI based on the selected bbox
roi = frame[y:y+h, x:x+w]
# Calculate the average pixel value in the ROI (16-bit)
avg_pixel_value = np.mean(roi)
print(f"Frame {i}: Average pixel value : {avg_pixel_value}")
print(f"Frame {i}: shape : {frame.shape}, data type : {frame.dtype}, min: {frame.min()}, max: {frame.max()}")
# Write the result to the CSV file
with open(csv_file, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([i, avg_pixel_value])
print(f"Finished processing all files.")
Подробнее здесь: [url]https://stackoverflow.com/questions/79235362/are-the-thermal-frames-being-converted-to-rgb-here[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия