python - Using PIL to insert greyscale image into RGB image by inserting greyscale values in RGB tuple -


i writing several functions, first 1 inserts greyscale bitmap image colour bitmap image. aim take each digit of greyscale pixel image (eg. 123) , replace end digit of every rgb pixel (244, 244, 244), end (241, 242, 243). watermarking colour image greyscale image.

the following code have far, i'm able return tuple values in list, not know how manipulate space size of smaller greyscale image in larger image.

def add_watermark():     image = image.open()     pixels = list(image.getdata())     image.putdata()     image.save()      in range(img.size[0]):         j in range(img.size[1]):             pixels[i,j] = (i, j, 100) 

can offer advice?

you're on right track. that's how manipulate pixels, though can little faster using pixel access objects i've shown below.

it's pretty straightforward except extracting , setting correct digits. in example, i've done dividing powers of 10 , using modulo operator, though there other ways. comments explain enough.

from pil import image  def add_watermark(watermark_path, image_in_path, image_out_path):     # load watermark , image , check sizes , modes     watermark = image.open(watermark_path)     assert watermark.mode == 'l'     image = image.open(image_in_path)     assert image.mode == 'rgb'     assert watermark.size == image.size      # pixel access objects     watermark_pixels = watermark.load()     image_pixels = image.load()      # watermark each pixel     x in range(image.size[0]):         y in xrange(image.size[1]):             # tuple of rgb values , convert list (mutable)             rgb = list(image_pixels[x, y])             i, p in enumerate(rgb):                 # divide watermark pixel 100 (r), 10 (g), 1 (b)                 # take modulo 10 last digit                 watermark_digit = (watermark_pixels[x, y] / (10 ** (2 - i))) % 10                 # divide , multiply value 10 0 last digit                 # add watermark digit                 rgb[i] = (p / 10) * 10 + watermark_digit             # convert tuple , store in image             image_pixels[x, y] = tuple(rgb)      # save image     image.save(image_out_path) 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -