# Fix "AttributeError: module 'scipy.misc' has no attribute 'imread'"

Yes. An agent swaps scipy.misc.imread and imsave for imageio, shows the saved image still matches the one in your repository, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/fix-scipy-misc-imread-attribute-error/scipy/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts from the script and the result files beside it. MarcoForte/knn-matting, a Python port of the KNN Matting paper, is one file. `knn_matting.py` reads `donkey.png` and `donkeyTrimap.png` with `scipy.misc.imread` at lines 48 and 49, solves for an alpha matte, and writes it with `scipy.misc.imsave` at line 51. The repository also contains `donkeyAlpha.png`, the output the author got. That file is the specification: a correct fix has to produce it again. On a current SciPy, `import scipy.misc` still succeeds with a DeprecationWarning that the module will be removed in 2.0.0, and the first `imread` call raises the error in the title.

Reading is the easy half, with one catch the agent checks before choosing a library. The trimap is a palette PNG. `imageio.imread` returns it as a 569 by 800 by 3 array, the same shape the old function gave, so the `[:,:,:3]` slice on line 49 keeps working. Opening it with Pillow and calling `np.array` returns a 569 by 800 array of palette indexes, and the slice fails. So the replacement for `imread` is imageio, as SciPy's own deprecation text said, and the agent states the shapes it printed for both inputs.

Writing is where the common fix goes wrong. The old `imsave` accepted a float array and rescaled it to 0 through 255 before saving. `imageio.imwrite('donkeyAlpha.png', alpha)` with the same float64 array raises `OSError: cannot write mode F as PNG` and leaves a zero-byte file behind. The array has to be converted first, and the conversion matters: on one and the same alpha array, `np.round(alpha * 255).astype(np.uint8)` matches the old `imsave` output in every one of the 455,200 pixels, while the shorter `(alpha * 255).astype(np.uint8)` truncates and differs by one grey level in 111,683 of them. The agent uses the rounding form and notes one more difference: the old function stretched whatever range it was given, so an array that only reached 0.5 was still saved with white at 255. The explicit conversion does not, which is correct for an alpha matte and worth a line in the pull request.

To get a baseline it builds two environments: Python 3.7 with SciPy 1.1.0, the last line that had these functions, and a current Python with current SciPy, scikit-learn and imageio. The old run exposes a second problem. `knn_matte` calls `warnings.filterwarnings('error')` and never restores the filters, so the `imsave` deprecation warning that follows becomes an exception and the demo dies after the solve. The filter is still installed when the function returns on the new stack too. The agent wraps that call in `warnings.catch_warnings()` so the setting stops leaking, reruns both environments, and compares: the old output differs from the committed `donkeyAlpha.png` in 3 pixels by one level, and the new stack's result differs from the old in 1,237 pixels by at most two, which is solver arithmetic and not the image code.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This script fails with \"AttributeError: module 'scipy.misc' has no attribute 'imread'\". Find every use of scipy.misc image functions (imread, imsave, imresize, imshow, toimage, fromimage, bytescale) and list them with file and line. If the repository contains output images the script produced, treat them as the expected result. Build two environments: one old enough that the functions exist (for example Python 3.7 with SciPy 1.1.0 and matching NumPy, scikit-learn and Pillow) and one with current releases. Run the script's computation in the old one and save the arrays and the output image as a baseline; if the old run fails for another reason, report it and work around it in your harness. Replace the reads with imageio and print the shape and dtype of every input under the old and new call, including any palette or greyscale file. Replace the writes with an explicit conversion to uint8 followed by imageio.imwrite. Before choosing the conversion, compare candidates against the old imsave output on the same array and report the number of differing pixels for each; say whether the old function rescaled the value range and whether your replacement does. Then run the whole script on current releases and compare its output with the baseline and with the committed image, separating differences caused by the image code from differences in numerical results. If the code changes global state such as warning filters, scope it and say so. Add the new dependency to the requirements the project documents. Open a pull request with the numbers; do not overwrite the committed result images.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that edits `knn_matting.py` in a handful of places: the two reads, the write with its conversion, the import inside the `__main__` block, and the scoped warning filter. The README's requirements list gains imageio. The description carries the shapes of both inputs under each reader, the pixel counts for the two conversions, the three-way comparison of old output, new output and committed image, and the traceback from the old environment that showed the leaking filter. The committed `donkeyAlpha.png` is not replaced.

A reviewer checks that the count for the chosen conversion is zero against the old function on the same array, and that the remaining differences are attributed to the solver with a maximum size. If the project relied on the old stretching of the value range somewhere, the pull request's note on that behaviour is where they would catch it. The baseline arrays and both output images are saved with the session as artifacts, so the comparison can be repeated without rebuilding a Python 3.7 environment.

## Run it on every script you hand off

This is a job you meet at your own terminal: you clone an old research repository, run it, and get the traceback. Hand it over from where you are. Rush is an MCP server, so an assistant in your terminal that has it connected with your API key can start the run as a tool call, passing the prompt above and your fork as the resource, and you carry on with something else. The session keeps going in its sandbox; read it later from the console or ask the same assistant to wait for it.

If you maintain several such repositories, send one request per repository from a short script instead. Give each a `request_id` that is a UUID so a retried call returns the run it already started, and let the key's concurrency limit queue the rest.

## Why run it on Rush?

The baseline needs an interpreter and a SciPy from 2018 next to current ones, and the solve itself builds a sparse system with one row per pixel. Few people keep a Python 3.7 environment around, and installing one on a laptop to fix a demo script is the step where the job gets abandoned. A Rush run has its own machine for both environments and the minutes the solves take, and the commands and their printed counts stay in the session's transcript.

It also answers the question a reader of the pull request will ask, which is whether the picture changed. An import swap can be reviewed by eye; a rounding change cannot. Because the run compares arrays and counts pixels against the file already in the repository, the claim that the output is the same comes with numbers and with the artifacts to recheck them.

## Frequently asked questions

### What replaces scipy.misc.imread?

`imageio.imread` for reading and `imageio.imwrite` for saving; SciPy's deprecation message named both. Reading is close to a drop-in. Saving is not, because `imwrite` will not take a float array for a PNG, so the values have to be scaled and converted to uint8 first.

### Why does imageio.imwrite fail with "cannot write mode F as PNG"?

The array is floating point and PNG has no float mode. The old SciPy function hid this by rescaling to bytes for you. Convert explicitly, with rounding, and the call succeeds. Remove the empty file the failed call leaves if your code checks for the output's existence.

### Can I just install an old SciPy?

Only with an old Python: the last SciPy line with these functions has no builds for current interpreters, which is why the agent uses Python 3.7 for the baseline. That is useful for comparison and a poor place to leave a project.

### What about scipy.misc.imresize?

It was removed with the others and has no single replacement, since it also rescaled values to bytes. The prompt asks the agent to list every such call. For a resize it compares a Pillow or scikit-image call against the old function's output on your images before choosing, the same way it does for saving.

## More SciPy jobs

- [Fix "ImportError: cannot import name 'simps' from 'scipy.integrate'" in SciPy 1.14](https://getrush.ai/run/fix-cannot-import-name-simps-from-scipy-integrate/scipy/)
- [Fix "NotImplementedError: interp2d has been removed in SciPy 1.14.0"](https://getrush.ai/run/fix-interp2d-has-been-removed/scipy/)

## More jobs like this: Hand off a long task

- [Fix "AttributeError: type object '_asyncio.Task' has no attribute 'all_tasks'" on Python 3.9 and Later](https://getrush.ai/run/fix-task-all-tasks-attribute-error/asyncio/)
- [Fix the ts-jest Config Under globals Is Deprecated Warning](https://getrush.ai/run/fix-ts-jest-config-under-globals-is-deprecated/ts-jest/)
- [Keep Supabase TypeScript Types in Sync With Your Migrations](https://getrush.ai/run/generate-database-types/supabase/)
- [Harden Docker Compose Services with Read-Only Filesystems and Dropped Capabilities](https://getrush.ai/run/harden-compose-services/docker-compose/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
