# ArrayCrop: anti ArrayPad, à la ImageCrop

**URL:** <https://community.wolfram.com/t/arraycrop-anti-arraypad-a-la-imagecrop/9157>\
**Category:** Ideas\
**Tags:** image-processing, symbolic-computations\
**Created:** [August 27, 2016, 11:32pm UTC](https://community.wolfram.com/t/arraycrop-anti-arraypad-a-la-imagecrop/9157 "2016-08-27T23:32:50Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Vitaliyk](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/vitaliyk/32/45591_2.png) [@Vitaliyk](https://community.wolfram.com/u/Vitaliyk)\
**Post date:** [August 27, 2016, 11:32pm UTC](https://community.wolfram.com/t/arraycrop-anti-arraypad-a-la-imagecrop/9157/1 "2016-08-27T23:32:50Z")

</div>

I sometimes need a function that would remove background of constant elements from an array, which surround a non-background array block. This is an opposite (so not always inverse) action to an `ArrayPad`. `ArrayCrop` is to `ArrayPad` as `ImageCrop` to `ImagePad`.

- **Did I miss a built-in function that allows to do this?**
- **Can function below be improved?**

While you ponder about it, I will share a version I wrote, at least for programming exercise sake. It is based on `SparseArray` as it contains all needed information about background. Here is the function:

```
Clear@ArrayCrop;

ArrayCrop[m_,v_]:=
Module[
	{
	ar=Most[ArrayRules[SparseArray[m, Automatic, v]]],
	corn
	},	
	
	corn=Map[Min,Transpose[ar[[All,1]]]];
	
	Normal[
		SparseArray[
			Rule@@@Thread[{
				Map[#-corn+1&,ar[[All,1]]],
				ar[[All,2]]
				}],
				Automatic,
				v
		]
	]
]

ArrayCrop[m_]:=ArrayCrop[m,0]

```

## 1D case

Automatic removal of 0:

```
l = ArrayPad[{x, y, z}, {2, 3}]
ArrayCrop[l]

Out[1]= {0, 0, x, y, z, 0, 0, 0}  
Out[2]= {x, y, z}

```

Specify element to remove:

```
l = ArrayPad[{x, y, z}, {2, 3}, w]
ArrayCrop[l, w]

Out[1]= {w, w, x, y, z, w, w, w}    
Out[2]= {x, y, z}

```

## 2D case

Automatic removal of 0, - note the 0-corner cases:

```
m = ArrayPad[{{0, x, 0}, {x, x, x}, {0, x, 0}}, {{1, 2}, {3, 4}}];
MatrixForm[m]
ArrayCrop[m] // MatrixForm

```

 ![ScreenShot2016-08-27at6.21.10PM.png](https://global.discourse-cdn.com/wolfram/original/3X/3/2/326eef01d29a623a4ff3e9e80a0529efa0594ca9.png)

Specify element to remove:

```
m = ArrayPad[{{w, x, w}, {x, x, x}, {w, x, w}}, {{1, 2}, {3, 4}}, w];
MatrixForm[m]
ArrayCrop[m, w] // MatrixForm

```

 ![ScreenShot2016-08-27at6.23.19PM.png](https://global.discourse-cdn.com/wolfram/original/3X/0/0/0060ed601207fe60dcf729c00595d0406d834823.png)

## 3D case

```
core = RandomInteger[2, {2, 3, 4}];
pad = ArrayPad[core, {{1, 1}, {1, 1}, {1, 1}}];
AbsoluteTiming[ArrayCrop[pad] === core]
Image3D[#, ImageSize -> 200] & /@ {core, pad, ArrayCrop[pad]}

```

 ![ScreenShot2016-08-27at6.25.55PM.jpg](https://global.discourse-cdn.com/wolfram/original/3X/c/2/c2873204203ee3dfb4370a4870bb64d83d1f0590.jpeg)

## 5D case

```
core = RandomInteger[9, {10, 20, 30, 40, 50}];
pad = ArrayPad[core, {{1, 1}, {2, 4}, {5, 6}, {7, 8}, {9, 10}}];
AbsoluteTiming[ArrayCrop[pad] === core]

Out[]= {25.0324, True}

```

---

<div class="post-metadata">

**Author:** ![halemichaeljr](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/halemichaeljr/32/22773_2.png) [@halemichaeljr](https://community.wolfram.com/u/halemichaeljr)\
**Post date:** [August 28, 2016, 2:21pm UTC](https://community.wolfram.com/t/arraycrop-anti-arraypad-a-la-imagecrop/9157/2 "2016-08-28T14:21:29Z")

</div>

Position and Extract allow a more direct approach than SparseArray while keeping the logic similar. Shorter code plus a 2-3x speedup on the 5D case makes a good trade I think.

```
ArrayCrop[a_, b_] :=
 Extract[a,
  Span @@@ MinMax /@
    Transpose@Position[a, Except@b, {-1}, Heads -> False]]

ArrayCrop[a_] := ArrayCrop[a, 0]

```

---

<div class="post-metadata">

**Author:** ![sghuisman](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/sghuisman/32/27850_2.png) [@sghuisman](https://community.wolfram.com/u/sghuisman)\
**Post date:** [August 29, 2016, 2:09pm UTC](https://community.wolfram.com/t/arraycrop-anti-arraypad-a-la-imagecrop/9157/3 "2016-08-29T14:09:46Z")

</div>

I don’t think you missed a particular function. Though it can be done faster. For one, you don’t need to scan/touch the ‘core’, I can just start looking at the edge, and once I see non-padding I don’t have to scan further. By cyclically Transposing the data I can check if that digit (array, matrix, hypermatrix) is only the padding stuff and if so, remove it. It can be done also without transposing but it is trickier…

```
$HistoryLength = 1;
ClearAll[ArrayCrop, DeleteStart, DeleteM, TransposeAndDelete]
DeleteStart[m_, pad_] := Module[{len},
  len = LengthWhile[m, MatchQ[Flatten[{#}], {pad ..}] &];
  Drop[m, len]
  ]
DeleteM[m_, pad_] := Reverse[DeleteStart[Reverse[DeleteStart[m, pad]], pad]]
TransposeAndDelete[m_, pad_] := DeleteM[Transpose[m, RotateLeft[Range[Depth[m] - 1]]], pad]
ArrayCrop2[m_, pad_] := Nest[TransposeAndDelete[#, pad] &, m, Depth[m] - 1]
ArrayCrop2[m_] := ArrayCrop2[m, 0]

```

1D:

```
core = {x, y, z};
l = ArrayPad[core, {2, 3}]
ArrayCrop[l] === ArrayCrop2[l] === core

```

2D:

```
core = {{0, x, y}, {x, x, x}, {0, x, 0}};
m = ArrayPad[core, {{1, 2}, {3, 4}}];
ArrayCrop[m] === ArrayCrop2[m] === core

```

5D:

```
core=RandomInteger[9,{10,20,30,40,50}];
pad=ArrayPad[core,{{1,1},{2,4},{5,6},{7,8},{9,10}}];
AbsoluteTiming[ac=ArrayCrop[pad];]
AbsoluteTiming[ac2=ArrayCrop2[pad];]
core===ac===ac2

```

5x speed up compared to your solution for big solutions, there may be room for more improvement by passing things by reference…

---

<div class="post-metadata">

**Author:** ![sghuisman](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/sghuisman/32/27850_2.png) [@sghuisman](https://community.wolfram.com/u/sghuisman)\
**Post date:** [August 29, 2016, 2:16pm UTC](https://community.wolfram.com/t/arraycrop-anti-arraypad-a-la-imagecrop/9157/4 "2016-08-29T14:16:02Z")

</div>

The **DeleteStart** function should be called **DropWhile** perhaps, but that is not (yet) an existing function but would fit in with **TakeWhile**.

---

<div class="post-metadata">

**Author:** ![sghuisman](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/sghuisman/32/27850_2.png) [@sghuisman](https://community.wolfram.com/u/sghuisman)\
**Post date:** [August 29, 2016, 2:41pm UTC](https://community.wolfram.com/t/arraycrop-anti-arraypad-a-la-imagecrop/9157/5 "2016-08-29T14:41:04Z")

</div>

Ok, without transposing I get a ~12x speed up:

```
ClearAll[ExtractND, LengthWhileN, ArrayCrop3]
ExtractND[m_, n_, i_] := Module[{spec},
  spec = ConstantArray[All, n];
  spec[[-1]] = i;
  Flatten[{Extract[m, spec]}]
  ]
LengthWhileN[m_, n_, pad_] := Module[{dims, dim, front, back},
  dims = Dimensions[m];
  dim = dims[[n]];
  front = LengthWhile[Range[dim], MatchQ[ExtractND[m, n, #], {pad ..}] &];
  back = LengthWhile[Range[dim], MatchQ[ExtractND[m, n, -#], {pad ..}] &];
  {front, back}
  ]
ArrayCrop3[m_] := ArrayCrop3[m, 0]
ArrayCrop3[m_, pad_] := Module[{d, padding},
  d = Depth[m] - 1;
  padding = LengthWhileN[m, #, pad] & /@ Range[d];
  padding++;
  padding[[All, 2]] *= -1;
  Extract[m, Span @@@ padding]
  ]

```

Which is roughly 12-13x faster for the large example… This is probably at the limits of speed you can get because in the end you have to check _something_. It leaves the entire core (except 1 ‘layer’) untouched, does not transpose. The code could be changed to crop at each level before going to the next level, this might speed things up a bit because the matrix would get smaller and smaller (if there is something to crop of course).
