翻转图像Python
我试图水平翻转图像.
由此: ????????????????? 对此: 但我一直在镜像中反映它. 像这样: 我试图扭转x轴索引,我不明白为什么它被分割. def flip(picture): height = getHeight(picture) width = getWidth(picture) newPicture = makeEmptyPicture(width,height) x2 = width-1 for x in range(0,width): y2 = 0 for y in range(0,height): pxl = getPixel(picture,x,y) newPxl = getPixel(picture,x2,y2) color = getColor(pxl) setColor(newPxl,color) y2 = y2+1 x2 = x2-1 return picture 我剩下的代码: def d(): f = pickAFile() picture = makePicture(f) newPicture = copy(picture) writePictureTo(newPicture,r"D:FOLDERnewPic4.jpg") explore(newPicture) 解决方法
在你的flip()函数中(比如在任何函数中),如其他答案所述,你返回的图片是作为函数参数传递的图像,但在d()中定义…
这是变量范围的问题,所以我邀请您再看看我们的讨论here. 在这里,你有两个选择(你在两者之间融化): >直接修改作为参数给出的图片 有关2d选项的详细信息: 这里重要的是图片变量属于d()函数(d()是它的范围).同时newPicture变量属于flip()函数(flip()是其范围).因此newPicture的生命周期是flip()(即,一旦你终止flip()函数的执行,它就会被破坏,同时返回).并且d()对这个newPicture一无所知,除非你把它返回到d(). 所以,简而言之(假设我们正在讨论第二种选择): 1)创建一个将图片作为参数的函数(flip()) 2)在flip()内部,创建一个局部变量newPicture并仅修改它,使原始图像保持不变 3)将新更新的newPicture返回到父作用域.这里d()调用flip(),因此它是父范围.我们必须创建一个3d变量(属于d()范围),以便掌握flip()返回的内容: def flip(picture) # Create newPicture # Modify newPicture (using the information from the "picture" parameter) setColor(newPicture,...) ... return newPicture def d(): file = PickAFile() original_pic = makePicture(file) finalNewPicture = flip(original_pic) # {1} show(finalNewPicture) {1}:这里我们将flip返回的值(即newPicture)分配给更高范围的变量finalNewPicture(handler)… 我希望它能帮助你理解这背后的逻辑.它就像俄罗斯娃娃:newPicture在flip()中使用,在d()中使用,… 编辑: 我还想对第一个选项做出解释…… 1)创建一个将图片作为参数的函数(flip()) 2)在flip()内部,直接修改更高范围的图片变量 3)不要从flip()返回任何内容 这将导致: def flip(picture) # Simply modify the variable "picture",given as a parameter setColor(picture,...) ... # Do not return anything def d(): file = PickAFile() original_pic = makePicture(file) flip(original_pic) # {1} show(original_pic) {1}:这里flip()直接在输入图片上进行了更改,因此我们可以直接显示原始修改后的图片(original_pic).不需要中间处理程序变量. 选项1的代码:(因为您已经为选项2工作了) def flip(picture): height = getHeight(picture) width = getWidth(picture) x2=width-1 for x in range(0,width/2): # Only process the half way y2=0 for y in range(0,height): # swap pix and pix2 pxl = getPixel(picture,y) pxl2 = getPixel(picture,y2) color = getColor(pxl) color2 = getColor(pxl2) setColor(pxl2,color) setColor(pxl,color2) y2=y2+1 x2=x2-1 def d(): f = pickAFile() original_picture = makePicture(f) flip2(original_picture) show(original_picture) d() 注意:翻页可以大致简化如下: def flip2(picture): height = getHeight(picture) width = getWidth(picture) for x in range(0,width/2): # Only process the half way for y in range(0,width-1-x,y) color = getColor(pxl) color2 = getColor(pxl2) setColor(pxl2,color2) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |