fantos commited on
Commit
6397ae5
·
verified ·
1 Parent(s): 3409808

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +35 -42
utils.py CHANGED
@@ -21,7 +21,7 @@ class WatermarkProcessor:
21
  def to_bin(self, data):
22
  """Convert data to binary format as string"""
23
  if isinstance(data, str):
24
- return ''.join(format(ord(char), '08b') for char in data)
25
  elif isinstance(data, bytes):
26
  return ''.join(format(x, '08b') for x in data)
27
  elif isinstance(data, np.ndarray):
@@ -81,8 +81,8 @@ class WatermarkProcessor:
81
  # Convert to string and add delimiter
82
  secret_data = json.dumps(data, ensure_ascii=False) + "###END###"
83
 
84
- # Convert to binary string
85
- binary_secret = ''.join(format(ord(char), '08b') for char in secret_data)
86
 
87
  # Check capacity
88
  if len(binary_secret) > image.shape[0] * image.shape[1] * 3:
@@ -94,12 +94,10 @@ class WatermarkProcessor:
94
  for j in range(image.shape[1]):
95
  for k in range(3):
96
  if data_index < len(binary_secret):
97
- # Get current pixel value
98
  pixel = image[i, j, k]
99
- # Clear the LSB by setting it to 0 and add the watermark bit
100
- pixel = (pixel & 0xFE) | (int(binary_secret[data_index]) & 0x01)
101
- # Ensure value stays within uint8 range
102
- image[i, j, k] = np.uint8(pixel)
103
  data_index += 1
104
  else:
105
  break
@@ -132,49 +130,44 @@ class WatermarkProcessor:
132
  if image is None:
133
  raise ValueError("Could not read image file")
134
 
135
- # Extract LSB from image
136
- binary_data = []
 
 
137
  for i in range(image.shape[0]):
138
  for j in range(image.shape[1]):
139
- for k in range(3): # RGB channels
140
- binary_data.append(str(image[i, j, k] & 1))
 
 
141
 
142
- # Convert bits to bytes
143
  bytes_data = bytearray()
144
  for i in range(0, len(binary_data), 8):
145
  if i + 8 <= len(binary_data):
146
- byte = ''.join(binary_data[i:i+8])
147
  bytes_data.append(int(byte, 2))
148
 
149
- # Find end marker in raw bytes
150
- end_marker = b'###END###'
151
- if end_marker in bytes_data:
152
- # Extract data before end marker
153
- data = bytes_data[:bytes_data.index(end_marker)]
154
  try:
155
- # Try to decode as UTF-8
156
- decoded_text = data.decode('utf-8', errors='ignore')
157
- try:
158
- # Try to parse as JSON
159
- json_data = json.loads(decoded_text)
160
- return json.dumps(json_data, ensure_ascii=False, indent=2)
161
- except json.JSONDecodeError:
162
- return decoded_text
163
- except UnicodeDecodeError:
164
- # If UTF-8 decoding fails, try decoding parts
165
- result = ''
166
- buffer = bytearray()
167
- for byte in data:
168
- buffer.append(byte)
169
- try:
170
- result += buffer.decode('utf-8')
171
- buffer.clear()
172
- except UnicodeDecodeError:
173
- if len(buffer) >= 4: # Max UTF-8 character length
174
- buffer.clear()
175
- continue
176
- return result if result else "Error: Invalid character encoding"
177
-
178
  return "Error: No valid watermark found"
179
 
180
  except Exception as e:
 
21
  def to_bin(self, data):
22
  """Convert data to binary format as string"""
23
  if isinstance(data, str):
24
+ return ''.join(format(x, '08b') for x in data.encode('utf-8'))
25
  elif isinstance(data, bytes):
26
  return ''.join(format(x, '08b') for x in data)
27
  elif isinstance(data, np.ndarray):
 
81
  # Convert to string and add delimiter
82
  secret_data = json.dumps(data, ensure_ascii=False) + "###END###"
83
 
84
+ # Convert string to bytes then to binary
85
+ binary_secret = ''.join(format(x, '08b') for x in secret_data.encode('utf-8'))
86
 
87
  # Check capacity
88
  if len(binary_secret) > image.shape[0] * image.shape[1] * 3:
 
94
  for j in range(image.shape[1]):
95
  for k in range(3):
96
  if data_index < len(binary_secret):
97
+ # Clear LSB and add watermark bit
98
  pixel = image[i, j, k]
99
+ pixel = (pixel & 0xFE) | int(binary_secret[data_index])
100
+ image[i, j, k] = pixel
 
 
101
  data_index += 1
102
  else:
103
  break
 
130
  if image is None:
131
  raise ValueError("Could not read image file")
132
 
133
+ # Extract LSB and build binary string
134
+ binary_data = ""
135
+ total_bits = image.shape[0] * image.shape[1] * 3
136
+
137
  for i in range(image.shape[0]):
138
  for j in range(image.shape[1]):
139
+ for k in range(3):
140
+ if len(binary_data) >= total_bits:
141
+ break
142
+ binary_data += str(image[i, j, k] & 1)
143
 
144
+ # Convert binary to bytes
145
  bytes_data = bytearray()
146
  for i in range(0, len(binary_data), 8):
147
  if i + 8 <= len(binary_data):
148
+ byte = binary_data[i:i+8]
149
  bytes_data.append(int(byte, 2))
150
 
151
+ # Early stopping if we find the end marker
 
 
 
 
152
  try:
153
+ if b'###END###' in bytes_data:
154
+ bytes_data = bytes_data[:bytes_data.index(b'###END###')]
155
+ break
156
+ except ValueError:
157
+ continue
158
+
159
+ try:
160
+ # Try UTF-8 decoding
161
+ decoded_text = bytes_data.decode('utf-8')
162
+ try:
163
+ # Try parsing as JSON
164
+ json_data = json.loads(decoded_text)
165
+ return json.dumps(json_data, ensure_ascii=False, indent=2)
166
+ except json.JSONDecodeError:
167
+ return decoded_text
168
+ except UnicodeDecodeError:
169
+ return "Error: Invalid character encoding"
170
+
 
 
 
 
 
171
  return "Error: No valid watermark found"
172
 
173
  except Exception as e: