Skip to content

Commit 820eacf

Browse files
authored
Optimize QRColorMask apply_mask method for enhanced performance
This commit introduces optimizations to the apply_mask method in the QRColorMask class to improve performance. Changes include: 1. Replacing getpixel and putpixel with direct pixel manipulation using the load() method, which speeds up the process. 2. Implementing a caching mechanism to reuse color transformations for identical pixel colors, reducing redundant calculations. 3. Adding conditions to skip processing for background color pixels to reduce computational load. These optimizations have significantly reduced the method's execution time. In some experiments, these changes have resulted in performance improvements of over ten times compared to the original method, especially for larger images.
1 parent d44a409 commit 820eacf

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

qrcode/image/styles/colormasks.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,22 +32,27 @@ def initialize(self, styledPilImage, image):
3232

3333
def apply_mask(self, image):
3434
width, height = image.size
35+
pixels = image.load()
36+
fg_color_cache = {}
3537
for x in range(width):
3638
for y in range(height):
37-
norm = self.extrap_color(
38-
self.back_color, self.paint_color, image.getpixel((x, y))
39-
)
39+
current_color = pixels[x, y]
40+
if current_color == self.back_color:
41+
continue
42+
if current_color in fg_color_cache:
43+
pixels[x, y] = fg_color_cache[current_color]
44+
continue
45+
norm = self.extrap_color(self.back_color, self.paint_color, current_color)
4046
if norm is not None:
41-
image.putpixel(
42-
(x, y),
43-
self.interp_color(
44-
self.get_bg_pixel(image, x, y),
45-
self.get_fg_pixel(image, x, y),
46-
norm,
47-
),
47+
new_color = self.interp_color(
48+
self.get_bg_pixel(image, x, y),
49+
self.get_fg_pixel(image, x, y),
50+
norm
4851
)
52+
pixels[x, y] = new_color
53+
fg_color_cache[current_color] = new_color
4954
else:
50-
image.putpixel((x, y), self.get_bg_pixel(image, x, y))
55+
pixels[x, y] = self.get_bg_pixel(image, x, y)
5156

5257
def get_fg_pixel(self, image, x, y):
5358
raise NotImplementedError("QRModuleDrawer.paint_fg_pixel")

0 commit comments

Comments
 (0)