pythonarraymerge
① python合并表格报错
你所定义的list node class和python自带的list type是不同的东西,不能通用,必须先转换
其他小错我直接帮你改掉了
下面是改好可以运行的代码:
class ListNode(object): def __init__(self,val): self.val = val self.next = None def __repr__(self): return str(self.val) def LinkedList(pythonlist): l = ListNode(pythonlist[0]) c = l for i in range(1,len(pythonlist)): l.next = ListNode(pythonlist[i]) l = l.next return c def PythonList(ListNode): l = [] while ListNode != None: l.append(ListNode.val) ListNode = ListNode.next return l class Solution(object): def mergeTwoLists(self,l1,l2): if l1 is None: return l2 if l2 is None: return l1 mmyhead=ListNode(0) mmyhead.next=None p=mmyhead while l1 is not None and l2 is not None: if l1.val<l2.val: p.next=l1 l1=l1.next else: p.next=l2 l2=l2.next p=p.next if l1 is not None: p.next=l1 else: p.next=l2 return mmyhead.next l1=LinkedList([1,3,5,7])l2=LinkedList([2,4,6,8])sol = Solution()print(PythonList(sol.mergeTwoLists(l1,l2)))
(LinkedList(pythonlist) 方法把一个传统的python list转换成你用的首位相衔的listnode 形式,PythonList(ListNode) 则是转换回来)
同时,linkedlist的数据类型在c里面比较常用,python里面一般用不着这么麻烦
希望对你有帮助
② 数据分析员用python做数据分析是怎么回事,需要用到python中的那些内容,具体是怎么操作的
最近,Analysis with Programming加入了Planet Python。我这里来分享一下如何通过Python来开始数据分析。具体内容如下:
数据导入
导入本地的或者web端的CSV文件;
数据变换;
数据统计描述;
假设检验
单样本t检验;
可视化;
创建自定义函数。
数据导入
1
这是很关键的一步,为了后续的分析我们首先需要导入数据。通常来说,数据是CSV格式,就算不是,至少也可以转换成CSV格式。在Python中,我们的操作如下:
import pandas as pd
# Reading data locally
df = pd.read_csv('/Users/al-ahmadgaidasaad/Documents/d.csv')
# Reading data from web
data_url = "https://raw.githubusercontent.com/alstat/Analysis-with-Programming/master/2014/Python/Numerical-Descriptions-of-the-Data/data.csv"
df = pd.read_csv(data_url)
为了读取本地CSV文件,我们需要pandas这个数据分析库中的相应模块。其中的read_csv函数能够读取本地和web数据。
1
既然在工作空间有了数据,接下来就是数据变换。统计学家和科学家们通常会在这一步移除分析中的非必要数据。我们先看看数据(下图)
对R语言程序员来说,上述操作等价于通过print(head(df))来打印数据的前6行,以及通过print(tail(df))来打印数据的后6行。当然Python中,默认打印是5行,而R则是6行。因此R的代码head(df, n = 10),在Python中就是df.head(n = 10),打印数据尾部也是同样道理
9
plt.show(sns.lmplot("Benguet", "Ifugao", df))
在Python中,我们使用def函数来实现一个自定义函数。例如,如果我们要定义一个两数相加的函数,如下即可:
def add_2int(x, y):
return x + y
print add_2int(2, 2)
# OUTPUT
4
顺便说一下,Python中的缩进是很重要的。通过缩进来定义函数作用域,就像在R语言中使用大括号{…}一样。这有一个我们之前博文的例子:
产生10个正态分布样本,其中和
基于95%的置信度,计算和;
重复100次; 然后
计算出置信区间包含真实均值的百分比
Python中,程序如下:
import numpy as np
import scipy.stats as ss
def case(n = 10, mu = 3, sigma = np.sqrt(5), p = 0.025, rep = 100):
m = np.zeros((rep, 4))
for i in range(rep):
norm = np.random.normal(loc = mu, scale = sigma, size = n)
xbar = np.mean(norm)
low = xbar - ss.norm.ppf(q = 1 - p) * (sigma / np.sqrt(n))
up = xbar + ss.norm.ppf(q = 1 - p) * (sigma / np.sqrt(n))
if (mu > low) & (mu < up):
rem = 1
else:
rem = 0
m[i, :] = [xbar, low, up, rem]
inside = np.sum(m[:, 3])
per = inside / rep
desc = "There are " + str(inside) + " confidence intervals that contain "
"the true mean (" + str(mu) + "), that is " + str(per) + " percent of the total CIs"
return {"Matrix": m, "Decision": desc}
上述代码读起来很简单,但是循环的时候就很慢了。下面针对上述代码进行了改进,这多亏了Python专家
import numpy as np
import scipy.stats as ss
def case2(n = 10, mu = 3, sigma = np.sqrt(5), p = 0.025, rep = 100):
scaled_crit = ss.norm.ppf(q = 1 - p) * (sigma / np.sqrt(n))
norm = np.random.normal(loc = mu, scale = sigma, size = (rep, n))
xbar = norm.mean(1)
low = xbar - scaled_crit
up = xbar + scaled_crit
rem = (mu > low) & (mu < up)
m = np.c_[xbar, low, up, rem]
inside = np.sum(m[:, 3])
per = inside / rep
desc = "There are " + str(inside) + " confidence intervals that contain "
"the true mean (" + str(mu) + "), that is " + str(per) + " percent of the total CIs"
return {"Matrix": m, "Decision": desc}
数据变换
创建自定义函数
③ python(pandas模块)
1.什么是pandas? numpy模块和pandas模块都是用于处理数据的模块。 numpy主要用于针对数组进行统计计算,处理数字数据比较方便。 pandas除了可以处理数字数据,还可...
④ python的image.merge去掉红色西数
纯净天空
当前位置: 首页>>代码示例>>Python>>正文
Python Image.merge方法代码示例
本文整理汇总了Python中PIL.Image.merge方法的典型用法代码示例。如果您正苦于以下问题:Python Image.merge方法的具体用法?Python Image.merge怎么用?Python Image.merge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PIL.Image的用法示例。
在下文中一共展示了Image.merge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: resolve
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def resolve(ctx):
from PIL import Image
if isinstance(ctx, list):
ctx = [ctx[0]]
net.load_parameters('superres.params', ctx=ctx)
img = Image.open(opt.resolve_img).convert('YCbCr')
y, cb, cr = img.split()
data = mx.nd.expand_dims(mx.nd.expand_dims(mx.nd.array(y), axis=0), axis=0)
out_img_y = mx.nd.reshape(net(data), shape=(-3, -2)).asnumpy()
out_img_y = out_img_y.clip(0, 255)
out_img_y = Image.fromarray(np.uint8(out_img_y[0]), mode='L')
out_img_cb = cb.resize(out_img_y.size, Image.BICUBIC)
out_img_cr = cr.resize(out_img_y.size, Image.BICUBIC)
out_img = Image.merge('YCbCr', [out_img_y, out_img_cb, out_img_cr]).convert('RGB')
out_img.save('resolved.png')
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:19,代码来源:super_resolution.py
示例2: distort_image
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def distort_image(im, hue, sat, val):
im = im.convert('HSV')
cs = list(im.split())
cs[1] = cs[1].point(lambda i: i * sat)
cs[2] = cs[2].point(lambda i: i * val)
def change_hue(x):
x += hue*255
if x > 255:
x -= 255
if x < 0:
x += 255
return x
cs[0] = cs[0].point(change_hue)
im = Image.merge(im.mode, tuple(cs))
im = im.convert('RGB')
return im
开发者ID:XiaoYee,项目名称:emotion_classification,代码行数:20,代码来源:utils.py
示例3: distort_image
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def distort_image(im, hue, sat, val):
im = im.convert('HSV')
cs = list(im.split())
cs[1] = cs[1].point(lambda i: i * sat)
cs[2] = cs[2].point(lambda i: i * val)
def change_hue(x):
x += hue*255
if x > 255:
x -= 255
if x < 0:
x += 255
return x
cs[0] = cs[0].point(change_hue)
im = Image.merge(im.mode, tuple(cs))
im = im.convert('RGB')
#constrain_image(im)
return im
开发者ID:andy-yun,项目名称:pytorch-0.4-yolov3,代码行数:21,代码来源:image.py
示例4: open_base_img
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def open_base_img(full_profile, res, base_color, color):
# get base image according to profile and perceptual gray of key color
base_num = str([0xE0, 0xB0, 0x80, 0x50, 0x20].index(base_color) + 1)
# open image and convert to Lab
with Image.open('images/{0}_{1}{2}.png'.format(*full_profile, base_num)) as img:
key_img = img.resize((int(s * res / 200) for s in img.size), resample=Image.BILINEAR).convert('RGBA')
if full_profile[1] in ('ISO', 'BIGENTER'): alpha = key_img.split()[-1]
l, a, b = ImageCms.applyTransform(key_img, rgb2lab_transform).split()
# convert key color to Lab
# a and b should be scaled by 128/100, but desaturation looks more natural
rgb_color = color_objects.sRGBColor(*ImageColor.getrgb(color), is_upscaled=True)
lab_color = color_conversions.convert_color(rgb_color, color_objects.LabColor)
l1, a1, b1 = lab_color.get_value_tuple()
l1, a1, b1 = int(l1 * 256 / 100), int(a1 + 128), int(b1 + 128)
# change Lab of base image to match that of key color
l = ImageMath.eval('convert(l + l1 - l_avg, "L")', l=l, l1=l1, l_avg=base_color)
a = ImageMath.eval('convert(a + a1 - a, "L")', a=a, a1=a1)
b = ImageMath.eval('convert(b + b1 - b, "L")', b=b, b1=b1)
key_img = ImageCms.applyTransform(Image.merge('LAB', (l, a, b)), lab2rgb_transform).convert('RGBA')
if full_profile[1] in ('ISO', 'BIGENTER'): key_img.putalpha(alpha)
return key_img
开发者ID:CQCumbers,项目名称:kle_render,代码行数:27,代码来源:key.py
示例5: __call__
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def __call__(self, video_path, frame_indices):
with h5py.File(video_path, 'r') as f:
flow_data = []
for flow in self.flows:
flow_data.append(f[f'video_{flow}'])
video = []
for i in frame_indices:
if i < len(flow_data[0]):
frame = [
Image.open(io.BytesIO(video_data[i]))
for video_data in flow_data
]
frame.append(frame[-1]) # add mmy data into third channel
video.append(Image.merge('RGB', frame))
return video
开发者ID:kenshohara,项目名称:3D-ResNets-PyTorch,代码行数:20,代码来源:loader.py
示例6: test_consistency_5x5
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def test_consistency_5x5(self):
source = Image.open("Tests/images/hopper.bmp")
reference = Image.open("Tests/images/hopper_emboss_more.bmp")
kernel = ImageFilter.Kernel((5, 5), # noqa: E127
(-1, -1, -1, -1, 0,
-1, -1, -1, 0, 1,
-1, -1, 0, 1, 1,
-1, 0, 1, 1, 1,
0, 1, 1, 1, 1), 0.3)
source = source.split() * 2
reference = reference.split() * 2
for mode in ['L', 'LA', 'RGB', 'CMYK']:
self.assert_image_equal(
Image.merge(mode, source[:len(mode)]).filter(kernel),
Image.merge(mode, reference[:len(mode)]),
)
开发者ID:holzschu,项目名称:python3_ios,代码行数:19,代码来源:test_image_filter.py
示例7: test_channels_order
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def test_channels_order(self):
g = Image.linear_gradient('L')
im = Image.merge('RGB', [g, g.transpose(Image.ROTATE_90),
g.transpose(Image.ROTATE_180)])
# Reverse channels by splitting and using table
self.assert_image_equal(
Image.merge('RGB', im.split()[::-1]),
im._new(im.im.color_lut_3d('RGB', Image.LINEAR,
3, 2, 2, 2, [
0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 1, 1,
1, 0, 0, 1, 0, 1,
1, 1, 0, 1, 1, 1,
])))
开发者ID:holzschu,项目名称:python3_ios,代码行数:18,代码来源:test_color_lut.py
示例8: wedge
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def wedge(self):
w = Image._wedge()
w90 = w.rotate(90)
(px, h) = w.size
r = Image.new('L', (px*3, h))
g = r.()
b = r.()
r.paste(w, (0, 0))
r.paste(w90, (px, 0))
g.paste(w90, (0, 0))
g.paste(w, (2*px, 0))
b.paste(w, (px, 0))
b.paste(w90, (2*px, 0))
img = Image.merge('RGB', (r, g, b))
return img
开发者ID:holzschu,项目名称:python3_ios,代码行数:24,代码来源:test_format_hsv.py
示例9: _fry
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def _fry(img):
e = ImageEnhance.Sharpness(img)
img = e.enhance(100)
e = ImageEnhance.Contrast(img)
img = e.enhance(100)
e = ImageEnhance.Brightness(img)
img = e.enhance(.27)
r, b, g = img.split()
e = ImageEnhance.Brightness(r)
r = e.enhance(4)
e = ImageEnhance.Brightness(g)
g = e.enhance(1.75)
e = ImageEnhance.Brightness(b)
b = e.enhance(.6)
img = Image.merge('RGB', (r, g, b))
e = ImageEnhance.Brightness(img)
img = e.enhance(1.5)
temp = BytesIO()
temp.name = 'deepfried.png'
img.save(temp)
temp.seek(0)
return temp
开发者ID:Flame442,项目名称:FlameCogs,代码行数:24,代码来源:deepfry.py
示例10: save_to_disk
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def save_to_disk(self, filename, format='.png'):
"""Save this image to disk (requires PIL installed)."""
filename = _append_extension(filename, format)
try:
from PIL import Image as PImage
except ImportError:
raise RuntimeError(
'cannot import PIL, make sure pillow package is installed')
image = PImage.frombytes(
mode='RGBA',
size=(self.width, self.height),
data=self.raw_data,
decoder_name='raw')
color = image.split()
image = PImage.merge("RGB", color[2::-1])
folder = os.path.dirname(filename)
if not os.path.isdir(folder):
os.makedirs(folder)
image.save(filename, quality=100)
开发者ID:felipecode,项目名称:coiltraine,代码行数:24,代码来源:sensor.py
示例11: from_png_to_bmp
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def from_png_to_bmp(png_path, output_path=BMP_IMAGE_TEST_TO_PATH):
"""
Convert a png_path image into a bmp 3-channel one and return the path to the converted image
:param png_path: path of the image
:param output_path: path in which we save the image
:return: the file path
"""
# convert a .png image file to a .bmp image file using PIL
file_name = os.path.splitext(png_path)[0] \
.split("/")[-1]
file_in = png_path
img = Image.open(file_in)
file_out = os.path.join(output_path, str(file_name), str(file_name) + '.bmp')
len(img.split()) # test
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.save(file_out)
else:
img.save(file_out)
return file_out
开发者ID:mawanda-jun,项目名称:TableTrainNet,代码行数:25,代码来源:inference_with_net.py
示例12: save_to_disk
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def save_to_disk(self, filename):
"""Save this image to disk (requires PIL installed)."""
filename = _append_extension(filename, '.png')
try:
from PIL import Image as PImage
except ImportError:
raise RuntimeError(
'cannot import PIL, make sure pillow package is installed')
image = PImage.frombytes(
mode='RGBA',
size=(self.width, self.height),
data=self.raw_data,
decoder_name='raw')
color = image.split()
image = PImage.merge("RGB", color[2::-1])
folder = os.path.dirname(filename)
if not os.path.isdir(folder):
os.makedirs(folder)
image.save(filename)
开发者ID:PacktPublishing,项目名称:Hands-On-Intelligent-Agents-with-OpenAI-Gym,代码行数:24,代码来源:sensor.py
示例13: distort_image
▲ 点赞 6 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def distort_image(im, hue, sat, val):
im = im.convert('HSV')
cs = list(im.split())
cs[1] = cs[1].point(lambda i: i * sat)
cs[2] = cs[2].point(lambda i: i * val)
def change_hue(x):
x += hue*255
if x > 255:
x -= 255
if x < 0:
x += 255
return x
cs[0] = cs[0].point(change_hue)
im = Image.merge(im.mode, tuple(cs))
im = im.convert('RGB')
return im
# generate random scale.
开发者ID:CharlesPikachu,项目名称:YOLO,代码行数:20,代码来源:utils.py
示例14: perform_inference
▲ 点赞 5 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def perform_inference(sym, arg_params, aux_params, input_img, img_cb, img_cr):
"""Perform inference on image using mxnet"""
metadata = onnx_mxnet.get_model_metadata('super_resolution.onnx')
data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]
# create mole
mod = mx.mod.Mole(symbol=sym, data_names=data_names, label_names=None)
mod.bind(for_training=False, data_shapes=[(data_names[0], input_img.shape)])
mod.set_params(arg_params=arg_params, aux_params=aux_params)
# run inference
batch = namedtuple('Batch', ['data'])
mod.forward(batch([mx.nd.array(input_img)]))
# Save the result
img_out_y = Image.fromarray(np.uint8(mod.get_outputs()[0][0][0].
asnumpy().clip(0, 255)), mode='L')
result_img = Image.merge(
"YCbCr", [img_out_y,
img_cb.resize(img_out_y.size, Image.BICUBIC),
img_cr.resize(img_out_y.size, Image.BICUBIC)]).convert("RGB")
output_img_dim = 672
assert result_img.size == (output_img_dim, output_img_dim)
LOGGER.info("Super Resolution example success.")
result_img.save("super_res_output.jpg")
return result_img
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:28,代码来源:super_resolution.py
示例15: color
▲ 点赞 5 ▼
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import merge [as 别名]
def color(src, target):
num_pixels = src.size[0] * src.size[1]
colors = src.getcolors(num_pixels)
rgb = sum(c[0] * c[1][0] for c in colors), sum(c[0] * c[1][1] for c in colors), sum(
c[0] * c[1][2] for c in colors)
rgb = rgb[0] / num_pixels, rgb[1] / num_pixels, rgb[2] / num_pixels
bands = target.split()
for i, v in enumerate(rgb):
out = bands[i].point(lambda p: int(p * v / 255))
bands[i].paste(out)
return Image.merge(target.mode, bands)
开发者ID:avrae,项目名称:avrae,代码行数:13,代码来源:playertoken.py
注:本文中的PIL.Image.merge方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。
©2008-2022 | 纯净天空 | 简体 | 繁体 | 联系我们 | 京ICP备15018527号-1 | 赞助商
⑤ php到底有多糟糕

php是web开发第一语言,这已经是坐稳了的事实,因为使用简单,工具完善,开发效率高等优点为它积聚了大量的粉丝,号称世界上最好的语言。 然而,就算是世界上最好的语言也有缺陷,下面我挑几个php语法层面不那么好用的特性吐槽下。
变量面前的美元($)符号
我想不明白当初php语言的设计师是怎么想的,为什么非要在变量名面前加上这个美元符号?每次我书写变量时必须要按一下shift +4键,用其它语言可以很流畅的写代码,在php中却老是被按这个shift打断整个过程,这除了能给程序员带来麻烦,我实在看不到有其它一丁点的好处。网上流传着的说法好像是因为带美元符号代码解析起来更容易, 性能更好。但是解释类型的语言又不只有php ,为什么其它语言就不用让程序员打这个讨厌的美元符号。每天看着满屏的美元符号,我口袋里的钱也没见多一分呀。
访问对象成员要使用箭头符号
明明按一下点号(.)就可以方便快捷的搞定的问题,却非要使用简单符号(->)来代替,真的是借我一百个脑袋也想不明白php设计者在设计这个特性是什么逻辑。难不成是因为php解释器最终会把php的代码转换成c代码执行,而c中访问指针的成员就是使用箭头符号的。如果是这样那显然是php的设计者们偷懒了,难到不能在转换成c执行的过程中多一步将点号转换为箭头符号的过程吗?不要告诉我又是因为性能问题而办不到,他们就不能为程序员想想?
数组即能当列表也能当字典
写一个函数,返回一个数组类型,但是在函数的外面,鬼知道这个数组是一个list还是一个map?写php代码不知道被这个特性坑过多少回,如果是别人写的函数, 又没有注释,那非得跑进函数里看个明白才知道应该这么样使用这个函数才是安全的。难到就不能把array拆成两个独立的类型分别代表list(列表)和map(字典)吗?这能为程序提供很大的便利,写的代码也更加不会出错。
匿名函数使用外部变量必须使用use关键字导入
这个特性不能说完全没有优点,对于代码的可维护性还是能起到正面的作用的,因为这么做能让我知道我在匿名函数体里面对于外部会有哪些依赖,让代码更可控。然而,这种写法真的是非常的不方便,每次写lambda时,要用到外部的变量时,都要使用use导入,把代码搞的看起来很臃肿,而且,因为其它语言没这个限制,习惯已经养成,所以每次都会忘记使用use导入,导致代码出错,增加排查问题的时间,这真的不是什么好玩的事。
用include导入文件
当把代码模块化时,然后在其它文件中使用,每次都需要使用这个include把文件导入进来,而且还要考虑路径的问题,在结构复杂的项目中,非常让人蛋疼。而像Java和Python之类的语言中,代码管理机制设计的非常好,想用什么import进来就可以了,根本不用考虑路径啊,文件名大小写啊之类的问题,能大大的提升开发效率。虽然,有框架可以解决这类问题,但毕竟是外部实现,使用起来总归不是那么顺畅。这也算是php一个比较大的毛病了。
总结的这五点算是php中存在问题的典范了,希望php团队能加把劲,把这些问题在未来的版本中优化掉,让开发者写代码时有更好的体验,更高的效率,让世界上最好的语言名副其实