@@ -283,7 +283,7 @@ def _make_image_packet(self, image: Image, threshold: int, red_threshold: int) -
283283 px = (x , y )
284284 r , g , b = pixels [px ]
285285
286- luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
286+ luminance = (( r * 38 ) + ( g * 75 ) + ( b * 15 )) >> 7
287287 if self .invert_luminance :
288288 if luminance < threshold :
289289 current_byte |= (1 << bit_pos )
@@ -314,19 +314,16 @@ def _make_image_packet(self, image: Image, threshold: int, red_threshold: int) -
314314 def _make_four_color_packet (self , pixels , width , height , threshold , red_threshold ) -> list [int ]:
315315 byte_data = []
316316 current_byte = 0
317- pixel_count = 0
317+ shift_counter = 3
318318
319- # 00: Black
320- # 01: White
321- # 10: Yellow
322- # 11: Red
323-
324- for y in range (height ):
325- for x in range (width ):
319+ for y in range (height - 1 , - 1 , - 1 ) if self .mirror_y else range (height ):
320+ for x in range (width - 1 , - 1 , - 1 ) if self .mirror_x else range (width ):
326321 r , g , b = pixels [(x , y )]
327322
328- # Logic from r.java
329- is_white = (((r * 38 ) + (g * 75 ) + (b * 15 )) >> 7 ) > threshold
323+ # Calculate weighted luminance for white detection
324+ luminance = ((r * 38 ) + (g * 75 ) + (b * 15 )) >> 7
325+
326+ is_white = luminance > threshold
330327 is_red = r > red_threshold
331328 is_green = g > red_threshold
332329 is_blue = b > red_threshold
@@ -337,23 +334,17 @@ def _make_four_color_packet(self, pixels, width, height, threshold, red_threshol
337334 if is_red and is_white :
338335 is_red = False
339336
340- val = 0
341- if is_green :
342- val = 2 # Yellow
343- elif is_red :
344- val = 3 # Red
345- elif is_white :
346- val = 1 # White
347- else :
348- val = 0 # Black
337+ # 00: Black, 01: White, 10: Yellow, 11: Red
338+ val = 2 if is_green else (3 if is_red else (1 if is_white else 0 ))
349339
350- shift = (3 - (pixel_count % 4 )) * 2
351- current_byte |= (val << shift )
340+ current_byte |= (val << (shift_counter * 2 ))
352341
353- pixel_count += 1
354- if pixel_count % 4 == 0 :
342+ if shift_counter == 0 :
355343 byte_data .append (current_byte )
356344 current_byte = 0
345+ shift_counter = 3
346+ else :
347+ shift_counter -= 1
357348
358349 return list (bytearray (byte_data ))
359350
0 commit comments