| 155 | self.pixels[x, y] = 0 |
| 156 | |
| 157 | def clean(self, allowed): |
| 158 | pixels = self.pixels |
| 159 | |
| 160 | w, h = self.img.size |
| 161 | |
| 162 | for x in range(w): |
| 163 | for y in range(h): |
| 164 | if pixels[x, y] == 255: |
| 165 | continue |
| 166 | #: No point in processing white pixels since we only want to remove black pixel |
| 167 | count = 0 |
| 168 | |
| 169 | try: |
| 170 | if pixels[x - 1, y - 1] != 255: |
| 171 | count += 1 |
| 172 | |
| 173 | if pixels[x - 1, y] != 255: |
| 174 | count += 1 |
| 175 | |
| 176 | if pixels[x - 1, y + 1] != 255: |
| 177 | count += 1 |
| 178 | |
| 179 | if pixels[x, y + 1] != 255: |
| 180 | count += 1 |
| 181 | |
| 182 | if pixels[x + 1, y + 1] != 255: |
| 183 | count += 1 |
| 184 | |
| 185 | if pixels[x + 1, y] != 255: |
| 186 | count += 1 |
| 187 | |
| 188 | if pixels[x + 1, y - 1] != 255: |
| 189 | count += 1 |
| 190 | |
| 191 | if pixels[x, y - 1] != 255: |
| 192 | count += 1 |
| 193 | |
| 194 | except Exception: |
| 195 | pass |
| 196 | |
| 197 | #: Not enough neighbors are dark pixels so mark this pixel |
| 198 | #: To be changed to white |
| 199 | if count < allowed: |
| 200 | pixels[x, y] = 1 |
| 201 | |
| 202 | #: Second pass: this time set all 1's to 255 (white) |
| 203 | for x in range(w): |
| 204 | for y in range(h): |
| 205 | if pixels[x, y] == 1: |
| 206 | pixels[x, y] = 255 |
| 207 | |
| 208 | self.pixels = pixels |
| 209 | |
| 210 | def derotate_by_average(self): |
| 211 | """ |