您的位置:首页 > 其它

Mathematica数字图像处理功能颇强(1)

2015-08-23 16:54 197 查看

来源

看到这样一个例子,如何把图片中的红球变成蓝色。



实现方法

目前三个答案里面最好的一个来自自称有“工程师强迫症”的@belisarius :思路是,先生成球的蒙板,再仅对特定区域的颜色作处理,这样就不会影响其它部分。

结果



2 . 代码

[code]i=Import["http://i.stack.imgur.com/Qr7Tx.jpg"];
getReds[x_Image]:=First@ColorSeparate[x,"Hue"]
isolateSphere[x_Image]:=SelectComponents[Binarize[getReds[x],.9],Large]
makeMask[x_Image]:=Image@Graphics[Disk@@(1/.ComponentMeasurements[isolateSphere[x],{"Centroid","BoundingDiskRadius"}]),{PlotRange->Thread[{1,#}],ImageSize->#}&@ImageDimensions@x]
getAreaToChange[x_Image]:=ImageMultiply[i,ColorNegate@makeMask[x]]
shiftColors[x_Image]:=Image[ImageData[getAreaToChange[x]]/.p:{r_,g_,b_}/;r>.3:>RotateLeft[p,1]]
finishIt[x_Image]:=ImageAdd[ImageMultiply[x,makeMask[x]],ColorConvert[shiftColors[x],"RGB"]]
{#,getReds@#,isolateSphere@#,makeMask@#,getAreaToChange@#,shiftColors@#,finishIt@#}&@i


这个例子只是让人感受一下, Mathematica中已经提供了足够强大的函数功能完成一些颇为复杂的数字图象处理过程。——自动从色调的二值化处理中获得蒙板,从而球的边缘部分过渡不自然是其缺点。

另外两个解答也很有特色,但是,从实现目标来说,我的个人观点觉得因为一个需要人为互动方式干预,另一个以代码简洁为特点而彻底作全局色调改变,都稍微逊色,但是,也能学到新东西:

这个方法可以动态调整色调的改变,但也是全局的:

[code]i=Import["http://i.stack.imgur.com/Qr7Tx.jpg"];

{h,s,b}=ColorSeparate[i,"HSB"];

colourchange[c_,from_,tol_,to_]:=Module[{offset=Mod[c-from+0.5,1]-0.5},If[Abs[offset]>tol,c,to]];

Manipulate[ColorCombine[{ImageApply[colourchange[#,ImageValue[h,pos],tol,ColorConvert[to,Hue][[1]]]&,h],s,b},"HSB"],{{to,Blue,"Change to"},Blue},{{tol,-0.01,"Tolerance"},-0.01,0.5},{{pos,{100,50}},Locator}]





色调加上了“人为”互动调整,如果细心,可以得到更佳的效果:



这个是只用了一行代码的 全局 方法, 改变了整幅图片的色调:

[code]i = Import["http://i.stack.imgur.com/Qr7Tx.jpg"];
Image[ImageData[i]/.{r_, g_, b_} /; r>g && r>b ->{b, g, r}]


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: