1
任务是制作两个功能,一个将灰度图像嵌入到RGB中。第二个显示隐藏的“水印”。我已经完成了任务(有15个测试代码必须通过,我将它们全部传递给D),但是如果可能的话,我想整理一下我的代码。有人告诉我,我可以使用裁剪功能将水印置于照片的上方(我不知道如何操作),而是使用了数学逻辑。在python(PIL)中将另一个图像放在另一个图像的上方,然后将另一个图像隐藏在另一个内部
from PIL import Image
#function for embedding the watermark
def add_watermark(clean_file, watermark_file):
#if the files are not compatible
#or doesn't exist end the function
try:
clean_photo = Image.open(clean_file)
watermark_photo = Image.open(watermark_file)
except:
return False
#the images pixels tuple values are attained
clean_photo_size = clean_photo.size
watermark_photo_size = watermark_photo.size
# .load was used to return a pixel access object
# that can be used to read and modify pixels
#for both images
photo_array = clean_photo.load()
watermark_array = watermark_photo.load()
#centring the watermarked image on the photo
start_x_coord=int((clean_photo_size[0]-watermark_photo_size[0])/2)
start_y_coord=int((clean_photo_size[1]-watermark_photo_size[1])/2)
#for the pixels that share the same position as the pixels in the
#watermark, manipulate their RGB tuple value to include the watermarks
#greyscale value as part of the original RGB tuple
for line in range(watermark_photo_size[0]):
for rank in range(watermark_photo_size[1]):
photo_array [(start_x_coord+line),\
(start_y_coord+rank)]\
=(int(((photo_array [(start_x_coord+line),\
(start_y_coord+rank)][0]/10)*10)\
+((watermark_array[line,rank]/100)%10)),\
int(((photo_array [(start_x_coord+line),\
(start_y_coord+rank)]\
[1]/10)*10)+((watermark_array[line,rank]/10)%10)),\
int(((photo_array [(start_x_coord+line),\
(start_y_coord+rank)][2]/10)*10)\
+(watermark_array[line,rank]%10)))
#create a new file name with _X at the end
new_File_Name = clean_file[:-4]+"_X"+clean_file[-4:]
#create a new file
clean_photo.save(new_File_Name)
#return true for the test
return True
我试图让这个职位的拼写和语法是正确的,但我一直清醒20小时,所以我现在很抱歉,如果我错过了什么。