fantos commited on
Commit
839bec8
ยท
verified ยท
1 Parent(s): 2697417

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +62 -33
utils.py CHANGED
@@ -16,10 +16,9 @@ def png_encode(im_name, extra):
16
  def to_bin(data):
17
  """Convert data to binary format as string"""
18
  if isinstance(data, str):
19
- # UTF-8๋กœ ์ธ์ฝ”๋”ฉํ•˜์—ฌ ๋ฐ”์ดํŠธ๋กœ ๋ณ€ํ™˜ ํ›„ ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜
20
- return ''.join(format(b, '08b') for b in data.encode('utf-8'))
21
  elif isinstance(data, bytes):
22
- return ''.join(format(i, "08b") for i in data)
23
  elif isinstance(data, np.ndarray):
24
  return [format(i, "08b") for i in data]
25
  elif isinstance(data, int) or isinstance(data, np.uint8):
@@ -46,6 +45,7 @@ def decode(image_name, txt=None):
46
  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
47
  binary_data = ""
48
 
 
49
  for row in image:
50
  for pixel in row:
51
  r, g, b = to_bin(pixel)
@@ -53,27 +53,50 @@ def decode(image_name, txt=None):
53
  binary_data += g[-1]
54
  binary_data += b[-1]
55
 
56
- # 8๋น„ํŠธ์”ฉ ๋ฌถ์–ด์„œ ๋ฐ”์ดํŠธ ๋ฐฐ์—ด ์ƒ์„ฑ
57
- bytes_array = bytearray()
58
  for i in range(0, len(binary_data), 8):
59
  byte = binary_data[i:i+8]
60
  if len(byte) == 8:
61
  try:
62
- bytes_array.append(int(byte, 2))
 
63
  except ValueError:
64
  continue
65
 
66
- # UTF-8๋กœ ๋””์ฝ”๋”ฉ
67
  try:
68
- decoded_data = bytes_array.decode('utf-8')
69
- if "=====" in decoded_data:
70
- decoded_data = decoded_data.split("=====")[0]
71
- if "#####" in decoded_data:
72
- decoded_data = decoded_data.split("#####")[0]
73
- return decoded_data
74
- except UnicodeDecodeError:
75
- # UTF-8 ๋””์ฝ”๋”ฉ์— ์‹คํŒจํ•œ ๊ฒฝ์šฐ
76
- return "Error: Invalid character encoding detected"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
  except Exception as e:
79
  return f"Error detecting watermark: {str(e)}"
@@ -90,31 +113,37 @@ def encode(image_name, secret_data, txt=None):
90
  # Calculate maximum bytes that can be encoded
91
  n_bytes = image.shape[0] * image.shape[1] * 3 // 8
92
 
93
- # UTF-8๋กœ ์ธ์ฝ”๋”ฉํ•˜์—ฌ ๋ฐ”์ดํŠธ ์ˆ˜ ๊ณ„์‚ฐ
94
- secret_bytes = secret_data.encode('utf-8')
95
- delimiter_bytes = "#####".encode('utf-8')
96
- end_marker_bytes = "=====".encode('utf-8')
97
 
98
- total_bytes = len(secret_bytes) + len(delimiter_bytes) + len(end_marker_bytes)
 
99
 
100
- if total_bytes >= n_bytes:
 
101
  return image_name, "Watermark is too large for Image Size"
102
-
103
- # Prepare binary data
104
- binary_secret_data = to_bin(secret_data) + to_bin("#####") + to_bin("=====")
105
- data_len = len(binary_secret_data)
106
  data_index = 0
 
107
 
108
- # Embed the secret data
109
  for i in range(image.shape[0]):
110
  for j in range(image.shape[1]):
111
- if data_index < data_len:
112
- # Modify the least significant bit of each color channel
113
- for k in range(3): # For each color channel (RGB)
114
- if data_index < data_len:
115
- image[i, j, k] = int(to_bin(image[i, j, k])[:-1] + binary_secret_data[data_index], 2)
 
 
 
 
 
116
  data_index += 1
117
-
 
 
118
  # Save the result
119
  output_path = "watermarked_image.png"
120
  cv2.imwrite(output_path, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
 
16
  def to_bin(data):
17
  """Convert data to binary format as string"""
18
  if isinstance(data, str):
19
+ return ''.join(format(x, '08b') for x in data.encode('utf-8'))
 
20
  elif isinstance(data, bytes):
21
+ return ''.join(format(x, '08b') for x in data)
22
  elif isinstance(data, np.ndarray):
23
  return [format(i, "08b") for i in data]
24
  elif isinstance(data, int) or isinstance(data, np.uint8):
 
45
  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
46
  binary_data = ""
47
 
48
+ # Extract binary data from image
49
  for row in image:
50
  for pixel in row:
51
  r, g, b = to_bin(pixel)
 
53
  binary_data += g[-1]
54
  binary_data += b[-1]
55
 
56
+ # Convert binary string to bytes
57
+ bytes_data = b''
58
  for i in range(0, len(binary_data), 8):
59
  byte = binary_data[i:i+8]
60
  if len(byte) == 8:
61
  try:
62
+ byte_val = int(byte, 2)
63
+ bytes_data += bytes([byte_val])
64
  except ValueError:
65
  continue
66
 
67
+ # Try to find the end marker in raw bytes
68
  try:
69
+ end_marker = b'====='
70
+ if end_marker in bytes_data:
71
+ bytes_data = bytes_data.split(end_marker)[0]
72
+
73
+ # Try to find the delimiter in raw bytes
74
+ delimiter = b'#####'
75
+ if delimiter in bytes_data:
76
+ bytes_data = bytes_data.split(delimiter)[0]
77
+
78
+ # Decode the bytes to string
79
+ decoded_text = bytes_data.decode('utf-8', errors='ignore')
80
+ return decoded_text.strip()
81
+
82
+ except Exception as e:
83
+ print(f"Decoding error: {e}")
84
+ # If regular decoding fails, try character by character
85
+ result = ""
86
+ current_bytes = bytearray()
87
+
88
+ for byte in bytes_data:
89
+ current_bytes.append(byte)
90
+ try:
91
+ char = current_bytes.decode('utf-8')
92
+ result += char
93
+ current_bytes = bytearray()
94
+ except UnicodeDecodeError:
95
+ continue
96
+
97
+ if result:
98
+ return result.strip()
99
+ return "Error: Could not decode watermark"
100
 
101
  except Exception as e:
102
  return f"Error detecting watermark: {str(e)}"
 
113
  # Calculate maximum bytes that can be encoded
114
  n_bytes = image.shape[0] * image.shape[1] * 3 // 8
115
 
116
+ # Prepare the data with delimiters
117
+ secret_data = str(secret_data)
118
+ complete_data = secret_data + "#####" + "====="
 
119
 
120
+ # Convert to binary
121
+ binary_secret_data = to_bin(complete_data)
122
 
123
+ # Check if the data can fit in the image
124
+ if len(binary_secret_data) > n_bytes * 8:
125
  return image_name, "Watermark is too large for Image Size"
126
+
 
 
 
127
  data_index = 0
128
+ binary_len = len(binary_secret_data)
129
 
130
+ # Embed the data
131
  for i in range(image.shape[0]):
132
  for j in range(image.shape[1]):
133
+ if data_index < binary_len:
134
+ pixel = image[i, j]
135
+ for color_channel in range(3):
136
+ if data_index < binary_len:
137
+ # Get the binary value of the pixel
138
+ binary_value = format(pixel[color_channel], '08b')
139
+ # Replace the least significant bit
140
+ binary_value = binary_value[:-1] + binary_secret_data[data_index]
141
+ # Update the pixel value
142
+ image[i, j, color_channel] = int(binary_value, 2)
143
  data_index += 1
144
+ else:
145
+ break
146
+
147
  # Save the result
148
  output_path = "watermarked_image.png"
149
  cv2.imwrite(output_path, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))