Task:
Given an image object and an effect identifier (string), apply the effect identified by the string on the image. The library of effects can grow as the program grows.
Code 1:
def apply_fx(img, fx):
if fx == 'sepia':
return sepia(img)
elif fx == 'b&w':
return contrast(grayscale(img), 2)
elif fx == 'faded':
return faded(img)
elif fx == 'hdr':
return hdr(img)
Code 2:
effects = {
'sepia': sepia,
'b&w': lambda x: contrast(grayscale(x), 2),
'faded': faded,
'hdr': hdr
}
def apply_fx(img, fx):
return effects[fx](img)
Opinion: I personally lean toward the second approach.
Note: the concern here generalizes to: dictionary of lambda
functions vs if-elif
in such scenarios.
Extra code: as suggested by @PeilonRayz.
sepia_filter = np.array([[.393, .769, .189],
[.349, .686, .168],
[.272, .534, .131]])
def sepia(img):
sepia_img = np.dot(img, sepia_filter.T)
return sepia_img / np.max(sepia_img)
sepia
etc. defined? Are they all on one class? Can they all be defined on one class? \$\endgroup\$apply_fx
also provided in the same module or is it defined in code importing the module? \$\endgroup\$