ahundt commited on
Commit
ba0e279
·
1 Parent(s): fb9d6a0

app.py simplify encode_image()

Browse files
Files changed (1) hide show
  1. app.py +3 -22
app.py CHANGED
@@ -73,31 +73,12 @@ def encode_image(data: np.ndarray, quality: int = 85) -> dict:
73
  if np.any(np.isnan(data)) or np.any(np.isinf(data)):
74
  raise ValueError("Input array contains NaN or Inf")
75
 
76
- # Data Type Handling and Scaling
77
- if np.issubdtype(data.dtype, np.floating):
78
- # Floating-point input: Use cv2.normalize (as before)
79
- if np.min(data) == np.max(data):
80
- scaled_data = np.full(data.shape, 0, dtype=np.uint8) if np.min(data) <=0 else np.full(data.shape, 255, dtype=np.uint8)
81
- else:
82
- scaled_data = cv2.normalize(data, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
83
-
84
- elif np.issubdtype(data.dtype, np.integer):
85
- # Integer input
86
- if data.dtype == np.uint8:
87
- # uint8: Skip normalization *unless* all values are the same
88
- if np.min(data) == np.max(data):
89
- scaled_data = np.full(data.shape, 0, dtype=np.uint8) if np.min(data) == 0 else np.full(data.shape, 255, dtype=np.uint8)
90
- else:
91
- scaled_data = np.ascontiguousarray(data) # Already uint8, just ensure contiguity
92
- else:
93
- # Other integer types: Convert to float64 for safe normalization
94
- scaled_data = cv2.normalize(data.astype(np.float64), None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
95
  else:
96
  raise TypeError("Input array must have a floating-point or integer data type.")
97
 
98
- scaled_data = np.ascontiguousarray(scaled_data)
99
-
100
-
101
  # JPEG Encoding (with quality control and error handling)
102
  try:
103
  retval, buf = cv2.imencode(".jpg", scaled_data, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
 
73
  if np.any(np.isnan(data)) or np.any(np.isinf(data)):
74
  raise ValueError("Input array contains NaN or Inf")
75
 
76
+ # Normalize and convert to uint8
77
+ if np.issubdtype(data.dtype, np.floating) or np.issubdtype(data.dtype, np.integer):
78
+ scaled_data = cv2.normalize(data, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  else:
80
  raise TypeError("Input array must have a floating-point or integer data type.")
81
 
 
 
 
82
  # JPEG Encoding (with quality control and error handling)
83
  try:
84
  retval, buf = cv2.imencode(".jpg", scaled_data, [int(cv2.IMWRITE_JPEG_QUALITY), quality])