Use loop instead of matrix computing for large images