1066 图像过滤 python

1066 图像过滤 (15 分)

图像过滤是把图像中不重要的像素都染成背景色,使得重要部分被凸显出来。现给定一幅黑白图像,要求你将灰度值位于某指定区间内的所有像素颜色都用一种指定的颜色替换。

输入格式:

输入在第一行给出一幅图像的分辨率,即两个正整数 M 和 N(0<M,N≤500),另外是待过滤的灰度值区间端点 A 和 B(0≤A<B≤255)、以及指定的替换灰度值。随后 M 行,每行给出 N 个像素点的灰度值,其间以空格分隔。所有灰度值都在 [0, 255] 区间内。

输出格式:

输出按要求过滤后的图像。即输出 M 行,每行 N 个像素灰度值,每个灰度值占 3 位(例如黑色要显示为 000),其间以一个空格分隔。行首尾不得有多余空格。

输入样例:

3 5 100 150 0
3 189 254 101 119
150 233 151 99 100
88 123 149 0 255

输出样例:

003 189 254 000 000
000 233 151 099 000
088 000 000 000 255
M,N,A,B,R=input().split()
M=int(M)
N=int(N)
A=int(A)
B=int(B)

ls_out=[]
for i in range(M):
    ls=input().split()
    for j in range(len(ls)):
        if len(ls[j])== 1:
            ls[j]='00'+ls[j]
        if len(ls[j])== 2:
            ls[j]='0'+ls[j]
        if int(ls[j])>=100 and int(ls[j])<=150:
            if len(R)==3:
                ls[j]=R
            if len(R)==2:
                ls[j]='0'+R
            if len(R)==1:
                ls[j]='00'+R
                
    ls_out.append(ls)

for i in range(M):
    print(' '.join(ls_out[i]))

错了一个测试点,超时一个测试点 

看了大神博主 BTboay 的代码,发现比我简单好多好多

照着大佬的思路写了一遍,最后一个点超时,而大佬的没超时,区别可能在于大佬没有2-5行的步骤,而是在用的时候直接从第一行input().split()这个列表里面用索引调

M,N,A,B,R=input().split()
M=int(M)
N=int(N)
A=int(A)
B=int(B)

ls_out=[]
for i in range(M):
    for j in input().split():
        if int(j)>=A and int(j)<=B:
            ls_out.append('0'*(3-len(R))+R)
        else:
            ls_out.append('0'*(3-len(j))+j)

for i in range(0,len(ls_out),N):
    print(' '.join(ls_out[i:i+N]))

猜你喜欢

转载自blog.csdn.net/weixin_43731183/article/details/86794646