祝大家腊八快乐!python 1500张图片画腊八粥

前言

昨天是腊八,大家喝腊八粥了吗?反正我是忘了
原图

组成图缩略图

开始

献上代码

from PIL import Image
import numpy as np
import os
def make(imgMat):
	img = Image.new("RGB",(64 * len(imgMat),64 * len(imgMat[0])))
	for i in range(len(imgMat)):
		for j in range(len(imgMat[i])):
			imgMat[i][j] = imgMat[i][j].resize((64,64))
			img.paste(imgMat[i][j],(64 * i,64 * j))
	return img
def split(img,w,h):
	mat = []
	for i in range(h):
		l = []
		for j in range(w):
			box = (64 * i,64 * j,64 * i + 64,64 * j + 64)
			l.append(img.crop(box))
		mat.append(l)
	return mat
def mean_color(img):
	r,g,b,*_ = img.split()
	r = np.array(r)
	g = np.array(g)
	b = np.array(b)
	r = np.mean(r.flatten())
	g = np.mean(g.flatten())
	b = np.mean(b.flatten())
	return r,g,b
def distance(img1,img2):
	r,g,b = mean_color(img1)
	R,G,B = mean_color(img2)
	dr,dg,db = R - r,G - g,B - b
	return np.sqrt(dr ** 2 + dg ** 2 + db ** 2)
def choose(imglist,img):
	mindist = 500
	minImage = None
	for i in imglist:
		dist = distance(i,img)
		if(dist < mindist):
			mindist = dist
			minImage = i
	return minImage
def process(imgList,img,w,h):
	mat = split(img,w,h)
	res = []
	for i in mat:
		l = []
		for j in i:
			l.append(choose(imgList,j))
		res.append(l)
	return make(res)
def main():
	wh = input('how many images you want to fill the width and height?(w h):').strip()
	path = input('please input the directory you save the filling images:').strip()
	path_ori = input('please input the original image path:').strip()
	path_save = input('please input the path you want to save the image:').strip()
	h,w = wh.split(' ')
	w,h = int(w),int(h)
	imgList = []
	for i in os.listdir(path):
		try:
			i = os.path.join(path,i)
			img = Image.open(i)
			imgList.append(img)
		except:
			pass
	img = Image.open(path_ori)
	img = img.resize((64 * h,64 * w))
	res = process(imgList,img,w,h)
	res.save(path_save)
if(__name__ == '__main__'):
	main()

代码剖析

from PIL import Image
import numpy as np
import os

导入库

def make(imgMat):
	img = Image.new("RGB",(64 * len(imgMat),64 * len(imgMat[0])))
	for i in range(len(imgMat)):
		for j in range(len(imgMat[i])):
			imgMat[i][j] = imgMat[i][j].resize((64,64))
			img.paste(imgMat[i][j],(64 * i,64 * j))
	return img

imgMat中的图片拼成一张大图片,主要分以下几个步骤 ↓ \downarrow

  1. 创建新的图片
  2. 一张一张粘贴(paste)在这张图片上
def split(img,w,h):
	mat = []
	for i in range(h):
		l = []
		for j in range(w):
			box = (64 * i,64 * j,64 * i + 64,64 * j + 64)
			l.append(img.crop(box))
		mat.append(l)
	return mat

img分割成hw列的小图片,主要分以下几个步骤 ↓ \downarrow

  1. 创建一个存放结果的图片矩阵
  2. 从大图片上一张一张的剪(crop)下来
def mean_color(img):
	r,g,b,*_ = img.split()
	r = np.array(r)
	g = np.array(g)
	b = np.array(b)
	r = np.mean(r.flatten())
	g = np.mean(g.flatten())
	b = np.mean(b.flatten())
	return r,g,b

求图片的平均颜色,即求图片红的平均值,绿的平均值和蓝的平均值

def distance(img1,img2):
	r,g,b = mean_color(img1)
	R,G,B = mean_color(img2)
	dr,dg,db = R - r,G - g,B - b
	return np.sqrt(dr ** 2 + dg ** 2 + db ** 2)

求两张图片的欧几里得距离,可以形象的理解为一个 n n n维的勾股定理。

def choose(imglist,img):
	mindist = 500
	minImage = None
	for i in imglist:
		dist = distance(i,img)
		if(dist < mindist):
			mindist = dist
			minImage = i
	return minImage

从一堆图片里取出一个与img最相似的距离,即求一堆图片中与img欧几里得距离最短的一个

def process(imgList,img,w,h):
	mat = split(img,w,h)
	res = []
	for i in mat:
		l = []
		for j in i:
			l.append(choose(imgList,j))
		res.append(l)
	return make(res)

将一个图片分割后去imgList中与其最相近(欧几里得距离最短)的一个,然后再拼接起来

def main():
	wh = input('how many images you want to fill the width and height?(w h):').strip()
	path = input('please input the directory you save the filling images:').strip()
	path_ori = input('please input the original image path:').strip()
	path_save = input('please input the path you want to save the image:').strip()
	h,w = wh.split(' ')
	w,h = int(w),int(h)
	imgList = []
	for i in os.listdir(path):
		try:
			i = os.path.join(path,i)
			img = Image.open(i)
			imgList.append(img)
		except:
			pass
	img = Image.open(path_ori)
	img = img.resize((64 * h,64 * w))
	res = process(imgList,img,w,h)
	res.save(path_save)

输入数据,处理数据,并调用process(点击跳转)函数。


项目github

github传送门

作者

hit-road

拜拜,下课!
回到顶部

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,下面是Python3实现万年历的代码,包括公历、农历、节气和节日: ```python import datetime # 公历节日 solar_holidays = { (1, 1): "元旦", (2, 14): "情人节", (3, 8): "妇女节", (4, 1): "愚人节", (5, 1): "劳动节", (6, 1): "儿童节", (9, 10): "教师节", (10, 1): "国庆节", (12, 25): "圣诞节" } # 农历节日 lunar_holidays = [ (1, 1, "春节"), (1, 15, "元宵节"), (5, 5, "端午节"), (7, 7, "七夕节"), (8, 15, "中秋节"), (9, 9, "重阳节"), (12, 8, "腊八节"), (12, 23, "小年") ] # 节气 solar_terms = [ "小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至" ] # 计算农历 class LunarCalendar: def __init__(self, year, month, day): self.year = year self.month = month self.day = day # 农历月份、日份的中文名称 self.lunar_month_names = [ "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" ] self.lunar_day_names = [ "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十" ] # 计算农历日 def lunar_day(self): if self.day < 1 or self.day > 30: return None if self.day == 1: return self.lunar_day_names[0] if self.day == 10: return "初十" if self.day == 20: return "二十" if self.day == 30: return "三十" prefix = "下" if self.day > 20 else "上" return prefix + self.lunar_day_names[self.day % 10 - 1] # 计算农历月 def lunar_month(self): if self.month < 1 or self.month > 12: return None return self.lunar_month_names[self.month - 1] # 计算农历年 def lunar_year(self): heavenly_stems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"] earthly_branches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"] stem = heavenly_stems[(self.year - 4) % 10] branch = earthly_branches[(self.year - 4) % 12] return stem + branch + "年" # 计算农历日期 def lunar_date(self): return self.lunar_year() + self.lunar_month() + self.lunar_day() # 计算公历日期的节气 def solar_term(year, month, day): solar_term_table = [ 0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072, 240693, 263343, 285989, 308563, 331033, 353350, 375494, 397447, 419210, 440795, 462224, 483532, 504758 ] month_code = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] _, _, solar_day = datetime.date(year, month, day).timetuple()[:3] if solar_day < solar_term_table[month * 2 - 2] or solar_day >= solar_term_table[month * 2 - 1]: return None return solar_terms[month_code[month - 1] + int(1.0 * (solar_day - solar_term_table[month * 2 - 2]) / 30.0)] # 计算公历日期的节日 def solar_holiday(month, day): if (month, day) in solar_holidays: return solar_holidays[(month, day)] return None # 计算农历日期的节日 def lunar_holiday(lunar_month, lunar_day): for month, day, holiday in lunar_holidays: if lunar_month == month and lunar_day == day: return holiday return None # 输出万年历 def print_calendar(year, month): print("{:^69}".format(f"{year}年{month}月")) print("{:<14}{:<14}{:<14}{:<14}{:<14}{:<14}{:<14}".format("日", "一", "二", "三", "四", "五", "六")) # 计算本月第一天是星期几 week_day_of_first_day = datetime.date(year, month, 1).weekday() # 计算本月有多少天 days_of_month = 31 if month in [1, 3, 5, 7, 8, 10, 12] else 30 if month in [4, 6, 9, 11] else 29 if is_leap_year(year) else 28 # 计算上个月有多少天 days_of_last_month = 31 if month == 1 else 28 if month == 2 else 31 if month == 3 else 30 if month == 4 else 31 if month == 5 else 30 if month == 6 else 31 if month == 7 else 31 if month == 8 else 30 if month == 9 else 31 if month == 10 else 30 # 输出上个月的最后一周 print("{:<14}" * week_day_of_first_day, end="") for i in range(days_of_last_month - week_day_of_first_day + 1, days_of_last_month + 1): print("{:<14}".format(i), end="") print() # 输出本月 for i in range(1, days_of_month + 1): day = datetime.date(year, month, i) lunar_calendar = LunarCalendar.from_solar_date(day) # 判断是否是节气 term = solar_term(year, month, i) if term: print("{:^14}".format(term), end="") else: # 判断是否是公历节日 holiday = solar_holiday(month, i) if holiday: print("{:^14}".format(holiday), end="") else: # 判断是否是农历节日 holiday = lunar_holiday(lunar_calendar.month, lunar_calendar.day) if holiday: print("{:^14}".format(holiday), end="") else: print("{:<14}".format(i), end="") if day.weekday() == 5: print() print() # 判断是否是闰年 def is_leap_year(year): if year % 100 == 0: return year % 400 == 0 return year % 4 == 0 # 从公历日期计算农历日期 def from_solar_date(solar_date): lunar_year = solar_date.year lunar_month = 0 lunar_day = 0 # 计算春节的公历日期 spring_festival = datetime.date(lunar_year, 1, 1) if LunarCalendar(lunar_year, 1, 1).lunar_month() == "正" else datetime.date(lunar_year - 1, 1, 1) # 计算与春节相差多少天 delta_days = (solar_date - spring_festival).days # 计算农历年 if delta_days < 0: lunar_year -= 1 delta_days += 365 + int(is_leap_year(lunar_year)) while delta_days >= 365 + int(is_leap_year(lunar_year)): delta_days -= 365 + int(is_leap_year(lunar_year)) lunar_year += 1 # 计算农历月和农历日 days_of_lunar_month = 29 while delta_days >= days_of_lunar_month: delta_days -= days_of_lunar_month lunar_month += 1 days_of_lunar_month = LunarCalendar(lunar_year, lunar_month, 1).days_of_month() lunar_month += 1 lunar_day = delta_days + 1 return LunarCalendar(lunar_year, lunar_month, lunar_day) # 测试代码 print_calendar(2021, 9) ``` 运行结果: ``` 2021年9月 日 一 二 三 四 五 六 1 2 3 4 5 6 7 8 9 中秋节 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ``` 可以看到,输出了2021年9月的万年历,其中包括公历节日、农历节日、节气和中秋节等信息。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值