如何使用numpy加速Python代码?

时间:2015-11-15 02:05:19

标签: python performance numpy

OrginalMutated是图片。 我需要分别得到每个r,g,b的差异。我得到了这个代码,但它很慢。任何有关快速制作的帮助都会很棒! :)

Orginal = np.asarray(Orginal).copy()
Mutated = np.asarray(Mutated).copy()    

Fittnes = 0

for x in range(0, 299):

    for y in range(0, 299):

        DeltaRed   = (Orginal[x][y][0] - Mutated[x][y][0])
        DeltaGreen = (Orginal[x][y][1] - Mutated[x][y][1])
        DeltaBlue  = (Orginal[x][y][2] - Mutated[x][y][2])

        Fittnes += (DeltaRed * DeltaRed + DeltaGreen * DeltaGreen + DeltaBlue * DeltaBlue)

return Fittnes

3 个答案:

答案 0 :(得分:3)

如果您没有进行额外的压缩,然后总结每个维度而不是使用numpy的和函数,那么它应该快得多:

DeltaRed   = np.sum(OR) - np.sum(MR)
DeltaGreen = np.sum(OG) - np.sum(MG)
DeltaBlue = np.sum(OB) - np.sum(MB)

答案 1 :(得分:1)

这是使用ndarray.sum进行一次求和的所有方法的一种方法 -

DeltaRed, DeltaGreen, DeltaBlue = Orginal.sum((0,1)) - Mutated.sum((0,1))

在处理uint8张图片时,其他人np.einsum并希望速度更快 -

org_diff = np.einsum('ijk->k',Orginal.astype('uint64'))
mut_diff = np.einsum('ijk->k',Mutated.astype('uint64'))
DeltaRed, DeltaGreen, DeltaBlue = org_diff - mut_diff

答案 2 :(得分:0)

这是从一开始就有用的代码。

   public class MyService extends Service {

    WindowManager.LayoutParams params;
    LayoutInflater li;

                @Override
                public void onCreate() {

                    super.onCreate();

        li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

            params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    700,
                    WindowManager.LayoutParams.TYPE_PHONE, 
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT);

            final WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

      final View view = li.inflate(R.layout.serviceeee, null); 

         ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);

             imageView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    MyService.this.stopSelf();// doesnt work...
                }
            });
        }
相关问题